Basic idea:
In the set of numbers to sort, select the minimum (or maximum) number to exchange with the 1th position, and then in the remaining number, find the smallest (or largest) number in the 2nd position, and so on, Until the first N-1 element (the penultimate number) and the nth element (the last number) are compared.
Examples of simple selection sorting:
Operation Method:
First trip, from N records to find the minimum key code record and the first record exchange;
Second, the second record from the beginning of the n-1 record to select the minimum key code record and the second record exchange;
And so on .....
On the first trip, the record with the smallest key code is selected from the N-i+1 record beginning with the first record, and the first record is exchanged,
Until the entire sequence is ordered by key code.
1 /**2 * @authorZhangtao3 */4 Public classSelectsort5 {6 Public Static voidMain (string[] args)7 {8 intArr[]={3,1,5,7,2,4,9,6,45,0,-1};9 selectsortcomplitient (arr);Ten } One //Simple Select sort sort A Static voidSelectsortcomplitient (int[] arr) - { - intArrlength=arr.length; the for(inti=0;i<arrlength;i++) - { - for(intj=i+1;j<arrlength;j++) - { + if(arr[i]>Arr[j]) - { + inttemp=Arr[i]; Aarr[i]=Arr[j]; atarr[j]=temp; - } - } - PrintLine (arr,i); - } - } in //Print the sort results each time - Static voidPrintLine (int[] arr,inti) to { +System.out.println (i+ ":"); - intArrlength=arr.length; the for(intj=0;j<arrlength;j++) * { $System.out.print (arr[j]+ "");Panax Notoginseng } - System.out.println (); the } +}
Simple selection of sorting, each loop can only determine the positioning of an element after sorting.
Simple selection sorting improvement--two Yuan Select sort
Simple selection of sorting, each loop can only determine the positioning of an element after sorting. We can consider improving the position of two elements (the current maximum and minimum records) for each cycle , thus reducing the number of cycles required for sorting. improved to sort n data, up to [N/2] loop. The specific implementation is as follows:
1 voidSelectsort (intR[],intN) {2 intI, J, Min, Max, TMP; 3 for(I=1; I <= n/2;i++) { 4 //do not exceed N/2 to select sort5min = i; max = i;//record the maximum and minimum keyword record locations separately6 for(j= i+1; j<= n-i; j + +) { 7 if(R[j] >R[max]) { 8max = J;Continue ; 9 } Ten if(r[j]<R[min]) { OneMin =J; A } - } - //This switching operation can also be discussed in order to improve the efficiency of theTMP = r[i-1]; R[I-1] = R[min]; R[min] =tmp; -TMP = R[n-i]; R[n-i] = R[max]; R[max] =tmp; - - } +}
Selection sort-simple Selection sort principle and Java implementation