小范围排序
时间复杂度
冒泡排序,选择排序不管原始序列怎么样,都是严格的O(N^2)
1 package com.hzf.sort; 2 3 import org.junit.Test; 4 5 public class ScaleSort { 6 public int[] sortElement(int[] A, int n, int distance) { 7 for (int i = 0; i < A.length - distance; i++) { 8 if (i == (A.length - distance -1)) { //如果只剩下最后k个数,使用插入排序 9 for(i = A.length - distance; i < A.length; i++){ 10 int j = i; 11 int target = A[j]; 12 while(j > 0 && A[j-1] > target){ 13 A[j] = A[j-1]; 14 j--; 15 } 16 A[j] = target; 17 } 18 break; 19 } 20 //如果不是剩下最后k个数,那么构建最小堆 21 buildMinHeap(A, i, distance+1); 22 } 23 return A; 24 } 25 26 public void swap(int[] arr, int m, int n) { 27 int temp = arr[m]; 28 arr[m] = arr[n]; 29 arr[n] = temp; 30 } 31 32 public void buildMinHeap(int[] arr, int oldIndex, int heapSize) { 33 34 int[] heapArr = new int[heapSize];//构建新的数组,便于构建最小堆 35 int m = 0; 36 37 //将传入的数组遍历到heapArr中 38 for(int i=oldIndex; i<(oldIndex+heapSize); i++){ 39 heapArr[m++] = arr[i]; 40 } 41 42 //从heapArr最后一个元素的父元素开始构建最小堆 43 int j = (heapArr.length - 1)/2; 44 int lastIndex = heapSize-1; 45 46 while(j >= 0){ 47 int rootIndex = j; 48 adjustHeap(heapArr, rootIndex, lastIndex); 49 j--; 50 } 51 //将构建好的最小堆赋值到原数组中 52 for(m=0; m<heapSize; m++){ 53 arr[oldIndex++] = heapArr[m]; 54 } 55 } 56 57 public void adjustHeap(int[] heapArr, int rootIndex, int lastIndex) { 58 int smallerIndex = rootIndex; 59 int leftChildIndex = rootIndex * 2 + 1; 60 int rightChildIndex = rootIndex * 2 + 2; 61 62 if(rightChildIndex <= lastIndex){//如果右孩子存在,那么左孩子一定存在 63 if(heapArr[rightChildIndex] < heapArr[rootIndex] || heapArr[leftChildIndex] < heapArr[rootIndex]){ 64 smallerIndex = heapArr[leftChildIndex] < heapArr[rightChildIndex] ? leftChildIndex : rightChildIndex; 65 } 66 }else if(leftChildIndex <= lastIndex){//其他情况,如果右孩子不存在,那么左孩子可能存在,如果左孩子存在,保证它不能越界 67 if(heapArr[leftChildIndex] < heapArr[rootIndex]){ 68 smallerIndex = leftChildIndex; 69 } 70 } 71 if(smallerIndex != rootIndex){//判断此时最大元素的下标是否改变,如果改变交换位置 72 swap(heapArr, rootIndex, smallerIndex); 73 adjustHeap(heapArr,smallerIndex,lastIndex);//一旦发生交换,那么子树可能不是最小堆(最大堆),接着往下调整 74 } 75 } 76 @Test 77 public void test() { 78 int[] a = new int[] { 3, 2, 1, 4, 11, 5, 10, 13, 12 }; 79 80 System.out.println("排序前"); 81 for (int temp : a) { 82 System.out.print(temp + " "); 83 } 84 85 sortElement(a, 9, 2);// 基数排序 86 87 System.out.println(" 排序后"); 88 for (int temp : a) { 89 System.out.print(temp + " "); 90 } 91 } 92 }
测试结果