Article Directory
Select sort Introduction
Principle:
each selection index of the current outer loop, the inner loop then, by determining, find the index of the position of the minimum or maximum; then exchanged on the two index values.
Improved bubble sort, from the number of exchanges O(N^2)
is reduced to O(N)
, while the number of comparisons is O(N^2)
, in fact, equal to the maximum number of switching N-1 or
Select from the front backwards
Select rear front; each inner loop index minimum is found, switching to the front, the front orderly
public void sort1(int[] ary) {
long startTime = System.nanoTime();
int selectIndex;
int len = ary.length;
for (int i = 0; i < len; i++) {
selectIndex = i;
for (int j = i + 1; j < len; j++) {
if (ary[selectIndex] > ary[j]) {
selectIndex = j; //每轮内层循环得到最小值的 index
}
//如下则是得到大的 index
// if (ary[j] > ary[selectIndex]) {
// selectIndex = j; //每轮内层循环得到最大值的 index
// }
}
if (selectIndex != i) {
Util.swap(ary, selectIndex, i);
}
// System.out.println(Arrays.toString(ary));
}
System.out.println("total time:" + ((System.nanoTime() - startTime) / 1.0e9));
}
Select from back to front
Selected from back; each inner loop index to find a maximum value, switching to the back, behind the orderly
public void sort2(int[] ary) {
long startTime = System.nanoTime();
int len = ary.length;
int selectIndex;
for (int i = len - 1; i >= 0; i--) {
selectIndex = i;
for (int j = i - 1; j >= 0; j--) {
if (ary[selectIndex] < ary[j]) {
selectIndex = j; //每轮内层循环得到最小值的 index
}
}
if (selectIndex != i) {
Util.swap(ary, selectIndex, i); //从后向前置换
}
// System.out.println(Arrays.toString(ary));
}
System.out.println("total time:" + ((System.nanoTime() - startTime) / 1.0e9));
}
Bubble sort performance (time consuming) Comparative
- Also completely reverse the order of the sequence
significantly better bubble sort - Fully random sequences
better than most of the bubble sort implemented; realized slightly worse than the optimal bubble sort