选择排序的核心思想就是从前往后依次找到最小的数放到前面,第一次找0~n-1之间最小的数放到0上;第二次找1~n-1之间最小的数放到1上,依次类推,但是只找n-1次,也是就是说最后一次不要找了,因为最后一个数字一定是有序的。
import java.util.Scanner;
public class SelectSort{
public static void main(String args[]){
Scanner scanner=new Scanner(System.in);
int total=scanner.nextInt();
int[] array=new int[1024];
for(int i=0;i<total;i++){
array[i]=scanner.nextInt();
}
selectSort(array,total);
output(array,total);
}
public static void output(int[] array,int total){
for(int i=0;i<total;i++){
System.out.print(array[i]+" ");
}
System.out.println();
}
public static void selectSort(int[] array,int total){
for( int i=0;i<=total-2;i++){
int minIndex=i;
for(int j=i+1;j<=total-1;j++){
if(array[minIndex]>array[j]){
minIndex=j;
}
}
if(minIndex!=i){
int temp=array[i];
array[i]=array[minIndex];
array[minIndex]=temp;
}
}
}
}
测试数据:
输入:
10
7 4 1 8 5 2 9 6 3 0
输出:
0 1 2 3 4 5 6 7 8 9
10
7 4 1 8 5 2 9 6 3 0
输出:
0 1 2 3 4 5 6 7 8 9