In a sorted family, choosing a sort is the simplest of all.
Its ideas (from small to Large):
- For a given set of records, after the first round of comparison, the minimum record is obtained, and then the record is exchanged with the position of the first record;
- Next the second round of records excluding the first record is obtained, and the minimum record is exchanged with the position of the second record;
- And so on, until all records are traversed.
Example:
Initialize: {5,1,2,4,3}
First round: {1,5,2,4,3}
Second round: {1,2,5,4,3}
Third round: {1,2,3,4,5}
Fourth round: {1,2,3,4,5}
Fifth round: {1,2,3,4,5}
You can see that the time complexity is 0 (N2), the space complexity 0 (1), the unstable sort, n is smaller when the performance is better.
Java Sample Code
Public classSort { Public Static voidSelectsort (int[] a) { intI, j, temp = 0, flag = 0, n =a.length; for(i = 0; i < n; i++) {Temp=A[i]; Flag=i; for(j = i+1; J < N; j + +) { if(a[j]<temp) {Temp=A[j]; Flag=J; } } if(Flag! =i) {A[flag]=A[i]; A[i]=temp; } } } Public Static voidMain (string[] args) {intA[] = {5,1,2,4,3}; Selectsort (a); for(inti = 0; i < a.length; i++) {System.out.print (A[i]+ " "); } System.out.println (); }}
Sort--Select sort