I wrote a program for Selection Sort.
SelectionSort finds small data and swaps elements in the first position. Since it is repeated, it is necessary to compare n ^ 2/2 times, and the amount of calculation is 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("Please enter the number of data");
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();
}
}
Recommended Posts