思路:
默认从小到大排序
- 角标0跟后面的所有的对比,如果前面比后面大,交换位置
- 之后角标1跟后面对比,如果前面比后面打,交换位置
- 以此类推
- 内循环结束,则最小的放在了角标0
代码
/** * Created by binfoo on 2016/7/10. */ public class SelectSort { /** * 选择排序 */ public static void selectSort(int[] arr) { for(int i = 0; i < arr.length - 1 ;i++){ for(int j = i+1;j<arr.length;j++){ if(arr[i]>arr[j]){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } } public static void printArray(int[] arr){ System.out.print("[ "); for (int i = 0 ;i < arr.length ;i++){ if(i < arr.length -1){ System.out.print(arr[i]+ ",");} else { System.out.print(arr[i]+" ]"); } } } public static void main(String[] args){ int[] arr = {2,43,55,5,22,33,88,1,0}; System.out.println("Before sort : "); printArray(arr); selectSort(arr); System.out.println(" After sort : "); printArray(arr); } }
验证
Before sort :
[ 2,43,55,5,22,33,88,1,0 ]
After sort :
[ 0,1,2,5,22,33,43,55,88 ]
Process finished with exit code 0