Java sorting algorithm (ii) direct selection of sorting
The basic operation of direct selection sorting is that each trip selects the smallest (or largest) element from the data element to be sorted, placing it at the end of the ordered sequence, until all the data elements to be sorted are finished, it needs to be n-1, the algorithm is unstable, O (1) additional space, The time complexity of the comparison is O (n^2), the time complexity of the interchange is O (n), and is not adaptive. It is not recommended in most cases. Can be used only if you want to reduce the number of exchanges.
Basic ideas
The direct selection of n records files can be sorted by n-1 direct selection to get ordered results
1. Initial state: Unordered area is r[1,n], ordered area is empty
2, the first trip sort
In the unordered area R[1,n] Select the smallest record of the keyword R[k], it will be swapped with the first record of the unordered area r[1], so that r[1,1 and R[]2..N] respectively into the number of records increased by 1 new ordered area and the number of records reduced by 1 new unordered areas.
。。。。。
3, the order of the first I trip
At the beginning of the sequencing sequence, the current ordered and unordered areas are r[1.i-1] and r[1<=i<=n-1]. The order selects the smallest record of the keyword from the current unordered area R[k], swapping him with the first record r of the unordered area, so that r[1..i] and r into the number of records increased 1 new ordered area and the number of records reduced by 1 new unordered area
So n record files can be directly selected sorted by N-1 Direct selection sort to get ordered results
Example code 1
Packagecom.spring.test;ImportJava.security.Principal;/*** Direct Select Sort Test Class*/ Public classSelectsorttest { Public Static voidMain (string[] args) {int[] data =New int[]{5, 3, 6, 2, 1, 9, 4, 8, 7}; print (data); Selectsort (data); print (data); } /*** Exchange of two data*/ Private Static voidSwapint[] Data,intIintj) { if(i = =j) { return ; } Data[i]= data[i]+Data[j]; DATA[J]= data[i]-Data[j]; Data[i]= data[i]-Data[j]; } /*** Sort an array*/ Private Static voidSelectsort (int[] data) { for(intI =0;i<data.length-1;i++){ intMinindex =i; for(intj=i+1;j<data.length;j++){ if(Data[j] <Data[minindex]) {Minindex=J; } } if(minindex!=i) {swap (Data,i,minindex); print (data); } } } /*** Print Array*/ Private Static voidPrintint[] data) { for(inti=0; I < data.length;i++) {System.out.print (Data[i]+ "\ T"); } System.out.println (); }}
Result of Operation
Java sorting Algorithm (ii): direct selection of sorting