Select sort can be divided into: simple selection sorting and heap sorting (known location, looking for elements) 1. Simple Selection sorting
principle : Simply select a minimum (maximum) number from the array you want to sort, and put it in the array until the array is sorted.
Code implementation:
for (int i=0;i< A.length-1;i++ int Smallest = I; for (int j=i+1;j <a.length;j++) { if (A[j] & Lt A[smallest]) {Smallest = J; }} if (Smallest!= i) {a[ I] = a[i] ^ A[smallest]; A[smallest] = a[i] ^ A[smallest]; A[i] = a[i] ^ A[smallest]; }}
Analysis : algorithmic instability (e.g. 5,2,5,1. First 5 and 1 swap), Spatial complexity O (1), Time complexity "best, average and worst O (n*n)"
2. Heap sorting (improvement of simple selection sorting)
principle : Constructs the sequence to be sorted into a large top heap. At this point, the maximum value of the entire sequence is the root node of the heap top. Remove it (in fact, it is exchanged with the end element in the heap array, at which point the element at the end is the maximum), and then the remaining n-1 sequences are re-formed into a heap, which gives the second-largest value in the N elements. With this repeated execution, an ordered sequence can be obtained.
Code implementation:
voidHeapsort (array[] a) {Moves the array backward one bit so that the element number starts at 1int[] arr =New int[A.length + 1]; for(inti = 0; i < a.length; i++) {Arr[i+1] =A[i]; } //first, the ordered sequence is built into a large top heap. for(inti = A.LENGTH/2; i > 0; i--) {heapadjust (arr, I, a.length); } //Sort for(intj = a.length; J > 1; j--) {swap (arr,1,J);//swaps the top element of the heap with the last element of the currently unsorted subsequenceHeapadjust (arr,1,j-1);//re-build the remaining n-1 sequence into a large top heap } //copy the ordered sequence to the original array for(inti = 0; i < a.length; i++) {A[i]= Arr[i+1]; }}voidHeapadjust (array[] A,intIintN) { intTMP = A[i];//temporary storage of the root node of the sequence to be adjusted for(intj = 2 * i; J <= N; J *= 2) {//filtering down a child node with a larger element if(J < n && A[j] < a[j+1]) {//Point J to a child with a larger element++J; } if(tmp <= A[J]) {//If the root node is smaller than the largest element in the child, assign the largest element of the child to the root nodeA[i] =A[j]; }Else{ Break;} I= J;//Keep J as the root node and continue to adjust its child nodes} A[i]= tmp;//assigns the value of the root node to the adjusted child node}
Analysis : Instability, Space cost O (1), Time complexity "best, average, worst of all Nlogn" advantages: Because the build heap spend more time, so adapt to large data volume sorting
Sorting algorithm of data structure and algorithm (iii): SELECT sort