思路
思路非常简单。就是第一轮循环选出最大的元素,第二轮循环选出第二大的元素。。。。
代码
package dataStructureAndAlgorithms;
public class SelectSort_heapSort {
public static void main(String args[]) {
int[] array = { 4, 2, 8, 9, 5, 7, 6, 1, 3 };
System.out.println("未排序数组顺序为:");
display(array);
System.out.println("-----------------------");
sort(array);
System.out.println("-----------------------");
System.out.println("经过简单选择排序后的数组顺序为:");
display(array);
}
// 选择排序
public static void sort(int[] array) {
int length = array.length;
// 最小值的下标
int minIndex = 0;
// 选出第i个位置上的元素。位置0上是最小的,1上是第二小的...最后一个位置上的元素不用选择
for (int i = 0; i < length - 1; i++) {
minIndex = i;
for (int j = i + 1; j < length; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
int temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
System.out.println("经过第" + (i + 1) + "轮排序后:");
display(array);
}
}
public static void display(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}
输出
未排序数组顺序为:
4 2 8 9 5 7 6 1 3
-----------------------
经过第1轮排序后:
1 2 8 9 5 7 6 4 3
经过第2轮排序后:
1 2 8 9 5 7 6 4 3
经过第3轮排序后:
1 2 3 9 5 7 6 4 8
经过第4轮排序后:
1 2 3 4 5 7 6 9 8
经过第5轮排序后:
1 2 3 4 5 7 6 9 8
经过第6轮排序后:
1 2 3 4 5 6 7 9 8
经过第7轮排序后:
1 2 3 4 5 6 7 9 8
经过第8轮排序后:
1 2 3 4 5 6 7 8 9
-----------------------
经过简单选择排序后的数组顺序为:
1 2 3 4 5 6 7 8 9