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 5 years have passed since last update.

BubbleSort

Posted at

ソートの復習がてら、BubbleSort(バブルソート)のプログラムを書いてみました。

バブルソートは、ソートのアルゴリズムの中で、1番理解しやすい簡単なアルゴリズムな気がします。

バブルソートは、リストの中の隣り合う要素を比較して、昇順または降順に並び替えるアルゴリズムで
す。

計算量はO(n^2)なので、早くはないですが、というよりソートの中でも遅い方ですが、やっていることが単純なので、比較的簡単で理解しやすいアルゴリズムだと思います。

BubbleSort.java

import java.util.*;
public class BubbleSort {
    static int debug = 0;
    public static void main(String[] args) {
	if (args.length > 0 ){
	    if(args[0].equals("-d")) debug = 1;
	    else if (args[0].equals("-d2")) debug = 2;
	}
	Scanner sc = new Scanner(System.in);
	System.out.print("データの個数を入力して下さい:");
	int n = sc.nextInt();
	int[] a = new int[n];
	for (int i=0; i<n; i++) a[i] = sc.nextInt();
	sort(a);
	System.out.println(toString(a));
    }
    public static void sort(int[] a) {
	for(int i = 0; i < a.length-1; i++) {
	    boolean flag = false;
	    for(int j=a.length-1;j>i; j--) {
		if(a[j-1] > a[j]){
		    int tmp = a[j];
		    a[j] = a[j-1];
		    a[j-1] = tmp;
		    flag = true;
		}
		if(debug > 1)
		    System.out.println("i="+i+",j="+j+": "+toString(a));
	    }
	    if(debug>0)
		System.out.print("sorting: "+toString(a));
	    if(!flag)break;
	}    
    }
    public static String toString(int[] a) {
	    StringBuffer sb = new StringBuffer();
	    for (int i=0;i<a.length;i++)
		sb.append(a[i] + " ");
	    return sb.toString();
    }
}

0
0
0

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?