publicstaticvoidswap(int []arr, int l, int r){ int temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; } publicstaticvoidshellSort(int []arr){ for (int gap = arr.length / 2; gap > 0; gap /= 2) for (int i = gap; i < arr.length; i++) for (int j = i - gap; j >= 0 && arr[j] > arr[j + gap]; j -= gap) swap(arr,j, j + gap); }
选择排序
每次从待排序的元素中选取最大(最小)的元素放到已排序序列的末尾。复杂度O(n^2)。是不稳定排序。
代码(java,以整型数据升序排序为例)
1 2 3 4 5 6 7 8 9 10
publicstaticvoidselectSort(int []arr){ for ( int i = 0 ; i < arr.length - 1 ; i++ ){ int min = i; for ( int j = i + 1 ; j < arr.length ; j++ ) if ( arr[j] < arr[min] ) min = j; if ( min != i ) swap(arr, i, min); } }
publicstaticvoidmergeSort(int []arr, int l, int r){ if ( l < r ){ int mid = ( l + r ) >> 1; mergeSort(arr, l, mid); mergeSort(arr, mid+1 , r); int l1 = mid - l + 1, l2 = r - mid; int i, j; int [] L = newint[l1+1], R = newint[l2+1]; for ( i = 0; i < l1 ; i++ ) L[i] = arr[l+i]; for ( j = 0; j < l2 ; j++) R[j] = arr[mid+j+1]; L[l1] = R[l2] = INF; i = j = 0; for ( int k = l ; k <= r ; k++){ if ( L[i] <= R[j] ) arr[k] = L[i++]; else arr[k] = R[j++]; } } }
publicstaticvoidMaxHeapify(int []arr, int i, int heapsize){ int l = Left(i), r = Right(i), largest = i; if ( l <= heapsize && arr[l] > arr[i] ) largest = l; if ( r <= heapsize && arr[r] > arr[largest] ) largest = r; if ( largest != i ){ swap(arr, i, largest); MaxHeapify(arr, largest,heapsize); } }
publicstaticintPartition(int []arr, int l, int r){ int cmp = arr[r]; int i = l - 1; for ( int j = l ; j < r ; j++ ) if ( arr[j] < cmp ) swap(arr, ++i, j); swap(arr, i+1, r); return i+1; } publicstaticvoidQuickSort(int []arr, int l, int r){ if ( l < r ){ int mid = Partition(arr, l, r); QuickSort(arr, l, mid-1); QuickSort(arr, mid+1, r); } }