I have to master some basic sorting algorithms, yes, that's what I mean, today I learned to choose the sorting algorithm.
First, the algorithm description
The smallest element in the array is first found, and it is exchanged with the first element of the group (if the first element is the smallest element then it is exchanged with itself). Find the smallest element in the remaining element, swap it with the second element, so repeat, the whole element is sorted, and this is called the selection sort, which is to ze the smallest of the remaining elements continuously.
Give me a chestnut:
Original array: 5, 2, 9, 6, 3 (first trip select minimum number to Exchange)
First trip: 2, 5, 9, 6, 3
Second trip: 2, 3, 9, 6, 5
Third Tour: 2, 3, 5, 6, 9
Four trips: 2, 3, 5, 6, 9
Second, the algorithm complexity analysis
Average time complexity: O (n^2)
Spatial complexity: O (1) (for Exchange and record indexing)
Stability: unstable (e.g. [5, 5, 3] The first trip will switch 5 and 3, invert the first 5 and move to the second 5 rear)
Third, the implementation of the algorithm (NO BB Show Your Code)
1 Packagecn.zpoor.Test;2 /**3 * @authorSchrödinger's Cat4 * Select Sort implementation*/5 Public classSelection {6 Public Static voidMain (string[] args) {7 int[] arr = {5,2,9,6,3};8System.out.println ("Before selecting sort:");9 for(intNum:arr) {TenSystem.out.print (num+ ""); One } A - //selecting an optimization for sorting - for(inti = 0;i<arr.length-1;i++) { the intK = i;//Record Value - for(intj = k+1;j<arr.length;j++) {//Select the minimum index value - if(arr[j]<Arr[k]) { -K = J;//record the index value of the smallest value found + } - } + //after the inner loop is finished, the minimum number of this round is found and the Exchange A if(i!=k) { at //Swap Location - inttemp =Arr[i]; -Arr[i] =Arr[k]; -ARR[K] =temp; - } - } in System.out.println (); -System.out.println ("After selecting sort:"); to for(intNum:arr) { +System.out.print (num + ""); - } the } * } $ /*Panax Notoginseng before selecting sort: - 5 2 9) 6 3 the after selecting sort: + 2 3 5) 6 9*/
Go to bed.
java-Selection Sorting algorithm