21030526【Java】バブルソート
お題
バブルソートで並び替える
ソース
import java.util.Random;
public class List1_1 {
// データの件数
private static final int N = 10;
private static int sort = new int[N];
private static void bubblesort() {
boolean flag;
do {
flag = false;
for(int i = 0; i < N - 1; ++i){
if(sort[i] > sort[i + 1]){
// 左右の並びがおかしければ入れ替える
flag = true;
int j = sort[i];
sort[i] = sort[i + 1];
sort[i + 1] = j;
}
}
}while(flag);
}
public static void main(String args) {
Random random = new Random();
System.out.println("ソート順序");
for(int i = 0; i < N; i++){
sort[i] = random.nextInt(1000);
System.out.println(sort[i] + " ");
}
System.out.println("\nソート開始");
bubblesort();
System.out.println("ソート終了");
for(int i = 0; i < N; i++){
System.out.println(sort[i] + " ");
}
}
}
実行結果
ソート順序
179
85
600
361
578
854
445
657
52
627
ソート開始
ソート終了
52
85
179
361
445
578
600
627
657
854