选择排序应该是最常想到的算法,先排好最大(最小)的元素,第二次排好次最大(次最小)的元素,依次将所有元素放好。
【代码】
public class SelectSort {
public static void main(String[] args){
int[] sort = {5,4,1,7,2,3};
System.out.println("before: " );
print(sort);
sort(sort);
System.out.println("after: " );
print(sort);
}
public static void sort(int[] s){
for(int i = 0; i < s.length - 1; i++){
int minIndex = i;
for(int j = i + 1; j < s.length ; j++){
if(s[minIndex] > s[j]){
minIndex = j;
}
}
if(minIndex != i){
swap(s,i,minIndex);
}
}
}
public static void swap(int[] s, int i, int j){
int temp = s[i];
s[i] = s[j];
s[j] = temp;
}
public static void print(int[] a){
for(int i : a){
System.out.println(i);
}
}
}