选择排序的简单实现
package com.dxscx.sort;
/**
* @Author: admin@dxscx.com
* @Time: 2016-8-11 下午3:34:26
* @Notice: What do you want to do?
* @Version: v1.0
*/
public class SelectSort {
/**
* @param args
*/
public static void main(String[] args) {
int[] nums = new int[] { 5, 4, 234, 43, 21, 1, 2, 1, 2, 1, 2, 12, 3,
32, 21, 3, 4, 23, 45, 5 };
sort(nums);
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i]+" ");
}
}
/**
* Name:select Sort
*
* Process:两层for循环嵌套, 将每次循环的最小值放在第一位(当然是置换--第一位和最小值位换值)
*
* 逻辑很好想到,第一次实现时忘了每次将第一位当作最小位和后面的值比较 难点:
*
* @param nums需要排序的数组
*
* @return 已经排序的数组
*/
private static int[] sort(int[] nums) {
for (int i = 0; i < nums.length; i++) {
// 每次执行完都把当前数组第一位当作最小值
int min_index = i;
for (int j = i; j < nums.length; j++) {
if (nums[min_index] > nums[j]) {// 找取最小值下标
min_index = j;
}
}
// 将当前首位置换成最小值
int temp = nums[i];
nums[i] = nums[min_index];
nums[min_index] = temp;
}
return nums;
}
}
执行结果
1 1 1 2 2 2 3 3 4 4 5 5 12 21 21 23 32 43 45 234