Brief
Selection sort is a simple sorting algorithm, which processes are as follows:
① find the smallest array element
② the first element of the array and its exchange
③ find the smallest element in the rest of the element
④ it and arrays a second switching element for
the next and so forth, until the entire array are ordered
example
Next we look at a specific example:
using the selected sorting array {S, O, R, T , E, X, A, M, P, L, E} ordered
Tips: i indicates the sort min represents the minimum number of index elements
I min. 1 0 2. 3. 4. 5. 6. 7. 8. 9 10
S O R & lt T a M P L E E X-
0. 6 X-S O R & lt T E a M P L E
. 1. 4 A O R T E X S M P L E
2 10 A E R T O X S M P L E
3 9 A And E T O X S M P L R
4 7 A And E L O X S M P T R
5 7 A E E L M X S O P T R
6 8 A E L E M O S X P T R
7 10 A E E L M O P X S T R
8 8 A E E L M O P R S T X
9 9 A E E L M O P R S T X
10 10 A E E L M O P R S T X-
---------------------------
sorting is done: A E E L M O P R S T X
Code Display
package Sort;
import java.util.*;
public class Selection_Sort {
//选择排序
public static void sort(Comparable[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
//将a[i]和a[i+1]到a[N]中的最小元素作交换
int min = i;
for (int j = i+1; j<N; j++) {
if ( a[j].compareTo(a[min]) < 0 )//如果a[j]<a[min]
min = j;
}
//将a[i]和a[min]调换位置
Comparable t = a[i];
a[i] = a[min];
a[min] = t;
}
}
//用于打印展示数组的方法
private static void show(Comparable[] a) {
for (int i = 0; i<a.length; i++)
System.out.print(a[i]+" ");
System.out.println();
}
//用例
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String in = reader.nextLine();
String[] a = in.split(" ");
sort(a);//调用上面的选择排序方法
show(a);
}
}
Input output
Input:
2,233,441,166,558,877
output:
1,122,334,455,667,788