0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C言語 バブルソート基本

Last updated at Posted at 2023-05-03

アルゴリズムの一つであるバブルソートを使った課題があったので、記録用にバブルソートの基本をメモしておきます。

この例は、[3,5,1,8,7]という数字のリスト(ここではnumbers)を昇降順、降下順に並び替えるものです。

bubblesort.c

#include <stdio.h>

int main(void){
    int a,b,c;
    int numbers[5] = {3,5,1,8,7};
    for(a = 0; a < 5; a++ ){
        for(b = a + 1; b < 5; b++ ){
            if (numbers[a] > numbers[b]){ //降順はif (numbers[a] < numbers[b])
                c = numbers[a];
    			numbers[a] = numbers[b];
    			numbers[b] = c;
            }
        }
    }
    
	for (a = 0 ; a < 5 ; a++)//並べ替えられたものを出力
	{
		printf("%d ", numbers[a]);
	}

	return 0;
}


結果(昇降順)

1 3 5 7 8 % 
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?