Select sort
Slogan
Knowledge point:
- Principle
- Algorithm
- Features
- Complexity
1.1Principle
First, find the smallest element in the array, and then swap it with the first element of the array (if the first element is the smallest element, it will be exchanged with itself ). Again, find the smallest element in the remaining element and swap it with the second element of the array. Until the entire array is sorted. This method is called selection sorting because it is constantly selecting the smallest of the remaining elements.
1.2
1.3Algorithm
|
Public ClassSelection {
Private Static BooleanLess (comparable V, comparable W ){
ReturnV. compareto (w) <0;
}
Private Static VoidExch (comparable [],IntI,IntJ ){
Comparable T = A [I];
A [I] = A [J];
A [J] = T;
}
Public Static VoidSort (comparable [] ){
// Sort a [] in ascending order
IntN = A. length;
For(IntI = 0; I <n; I ++ ){
IntMin = I;
For(IntJ = I + 1; j <n; j ++)
If(Less(A [J], a [Min])
Min = J;
Exch(A, I, min );
}
}
} |
1.4Features
The running time is irrelevant to the input.Scanning an array to find the smallest element does not provide any information for the next scan. This nature is a disadvantage in some cases, because people who use the sort option may be surprised to find that, the sorting time of an ordered array or an array with all the same primary keys is as long as that of an array with random elements! We will see that other algorithms are better at using the initial state of input.
Data movement is minimal.Each exchange changes the values of two array elements. Therefore, N exchanges are used for sorting. The number of exchanges and the size of the array areLinear Relationship. Any other algorithm we will study does not have this feature (most of the increase orders of magnitude are linear logarithm or square level ).
Sort -- select sort