LoginSignup
0
0

More than 5 years have passed since last update.

SelectionSort

Posted at

SelectionSortのプログラムを書いてみました。

SelectionSort(選択ソート)は、小さいデータを見つけて、最初の位置の要素を入れ替えていきます。
それを繰り返していくので、n^2/2回の比較が必要になり、計算量はO(n^2)です。

SelectionSort.java
import java.util.*;
public class SelectionSort {
    static boolean debug = false;
    public static void main(String[] args) {
    if (args.length > 0 && args[0].equals("-d")) debug = true;
    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++) {
        int k = i;
        for(int j = i + 1; j < a.length; j++) {
        if(a[k] > a[j]) k = j;      
        }
        int tmp = a[i];
        a[i] = a[k];
        a[k] = tmp;
        if(debug) { System.out.println("sorting: " + toString(a)); }
    }
    }
    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