Algorithm implementation:
Red Book version:
public class selection{ static void sort (comparable[] a) {int n=a.length; for (int I=0;i<n;i++ int min=i; for (int J=i+1;j<n;j++) if (Lessa ([j],a[min]) min =j ; Exch (A,i,min); } }}
An int array-based implementation:
Public Static voidSelectsort (int[]a] { intMinindex=0; intTemp=0; if((a==NULL)|| (a.length==0)) return; for(inti=0;i<a.length-1;i++) {Minindex=i;//subscript for the smallest array of data in unordered regions for(intj=i+1;j<a.length;j++) { //find the smallest data in an unordered area and save its array subscript if(a[j]<A[minindex]) {Minindex=J; } } if(minindex!=i) {//if the minimum value of the unordered area is not the default first data, then the interchange. temp=A[i]; A[i]=A[minindex]; A[minindex]=temp; } }}
Note: Removing the former definition of less (comparable a, comparable b) and Exch (comparable[] A,int a,int b) simplifies the code, and there is a literal difference, that is, the decision condition in the outer for loop is I<n , the other is i<n-1; in fact i=n-1, the last number that needs to be compared must already be the biggest number, do not need to exchange; but there is only one comparison operation, and there is no essential difference between the two.
The essence of the selection sort is to start with the first bit, all the remaining elements after the traversal, to find the smallest one in the first place, and then start with the second, find the second-smallest number in the array, and so on.
There are two important features in selecting a sort:
- Run time and input Independent
That is, regardless of the order of the initial state of the array, the number of comparisons of the selected sort has not changed. Considering that the relationship between the number of comparisons and the number of elements is N²/2, it is not a good deal to use selection sorting for an already ordered array.
2. Minimal movement of data
The number of move operations is a constant, up to N, and none of the other algorithms have this feature.
Select sort basis (Java implementation)