选择排序思想:
数组长度为L,做(L-1)趟的选择,把最小的元素放在有序数组的后面(无序数组的首位)。
这样,每趟需要做(L-1)~1次比较,总共做L*(L-1)/2次比较,时间复杂度O(N*N),空间复杂度O(1),是一种稳定的排序。
数组长度为L,做(L-1)趟的选择,把最小的元素放在有序数组的后面(无序数组的首位)。
这样,每趟需要做(L-1)~1次比较,总共做L*(L-1)/2次比较,时间复杂度O(N*N),空间复杂度O(1),是一种稳定的排序。
/**
* SelectSort.java
*
* 该类实现选择排序.
* i.e: java SelectSort 3 2 1 4 5 6
*
* @author Administrator
*/
public class SelectSort {
/**
* 选择排序一个数组。
*/
public static void selectSort(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
int k = selectMinIndex(a, i, a.length - 1);
if (i != k)
Util.swap(a, i, k);
}
}
/**
* 该方法返回数组(下标范围i~j)中最小值的下标。
*/
private static int selectMinIndex(int[] a, int i, int j) {
int minIndex = i;
for (int p = i; p < j; p++)
if (a[minIndex] > a[p + 1])
minIndex = p + 1;
return minIndex;
}
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("请输入数字以空格隔开");
System.exit(-1);
}
int[] a = new int[args.length];
for (int i = 0; i < args.length; i++)
a[i] = Integer.parseInt(args[i]);
SelectSort.selectSort(a);
// 输出排序后的数组元素。
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
}

被折叠的 条评论
为什么被折叠?



