[JAVA] Selection Sort

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

Selection Sort
Selection sort O (n ^ 2)
sort
Multi-stage selection
Insertion sort
[Python] Sort
Natural sort
Python # sort
Bubble sort
Bubble sort
I wrote the selection sort in C
AOJ Sort I-
Feature Selection Datasets
Algorithm learned with Python 15th: Sorting (selection sort)
Merge Sort Explained
Insertion sort implementation
Hands-on sleep sort
Sort by pandas
I tried to implement selection sort in python
visualize insertion sort
Bubble sort, selection sort, insertion sort, shell sort, merge sort, quick sort, count sort (Python)