Select Sort:
Principle: The index of the larger/smaller element is saved if it is greater than/less (depending on whether the ascending or descending order is required) from the leftmost element of the array, in turn, from the element at the left of the following position.
When a comparison is completed, the index of the larger/smaller element to be saved is substituted with the left element of the start comparison
Improved bubbling sorting, the number of exchanges reduced from O (n^2) to O (N), and the number of comparisons is O (n^2)
/** * Select sort * Compare times O (n^2), swap O (N) * @author Stone * */public class Selectionsort {public static void main (string[] args) { int len = 15;int[] ary = new Int[len]; Random random = new random (), for (int j = 0; J < Len; J + +) {Ary[j] = random.nextint (1000);} SYSTEM.OUT.PRINTLN ("-------------before sorting");//ary=new int[]{10,9,8,7,6,5,4,3,2,1}; Number of test exchanges//ary=new int[]{1,2,3,4,5,6,7,8,10,9}; Test the number of interchanges for (int j = 0; J < Ary.length; J + +) {System.out.print (Ary[j] + "");} Selectdesc (ary); selectasc (ary);} /* Select sort: Descending */static void Selectdesc (int[] ary) {int comparecount = 0;//comparison int changecount = 0;//interchange int len = Ary.lengt H;int Maxvalueindex =-1; Records a comparison of the lowest-value index for (int i = 0; i < len-1; i++) {maxvalueindex = i;//starting from 0 for (int j = i + 1; j < Len; J + +) {if (a Ry[maxvalueindex] < Ary[j]) {maxvalueindex = J;//record large index comparecount++;}} System.out.println ("minvalueindex==" + Maxvalueindex); Ary[i] = Ary[maxvalueindex] + (Ary[maxvalueindex] = ary[i]) * 0 ;//One-step Exchange changecount++;} System.out.println ("\ n-------------Comparison after descending sort: "+ Comparecount +", interchange "+ Changecount); for (int j = 0; J < Ary.length; J + +) {System.out.pri NT (Ary[j] + "");}} /* * Select sort: Ascending */static void Selectasc (int[] ary) {int comparecount = 0, Changecount = 0;int len = Ary.length;int Minindex = -1;for (int i = 0; i < len-1; i++) {minindex = i;for (int j = i + 1; j < Len; J + +) {if (Ary[minindex] > Ary[j] {Minindex = j;//record smaller index comparecount++;}} Ary[i] = Ary[minindex] + (Ary[minindex] = ary[i]) * 0;changecount++;} System.out.println ("\ n-------------Comparison in ascending order:" + Comparecount + ", interchange" + Changecount); for (int j = 0; j < Ary.length; J + +) {System.out.print (Ary[j] + "");}}}
Print
Java implementation Selection Sorting