//直接插入法排序。依次从原来数组中选取元素插入排序后的数组(从后往前找插入位置) public static int[] insertSort(int[] nums) { if(nums == null || nums.length == 0 || nums.length == 1) return nums; int temp = 0; for(int i=1; i<nums.length; i++) { if(nums[i] < nums[i-1]) { temp = nums[i]; int j = i-1; do { nums[j+1] = nums[j]; j--; } while(j >= 0 && nums[j] > temp); nums[j+1] = temp; } } return nums; } //折半插入排序,每次寻找插入位置时用二分查找的方法 public static int[] binaryInsertSort(int[] nums) { if(nums == null || nums.length == 0 || nums.length == 1) return nums; int temp = 0; for(int i=1; i<nums.length; i++) { if(nums[i] < nums[i-1]) { temp = nums[i]; int low = 0, high = i-1; while(low < high) { int mid = (low + high) / 2; if(temp < nums[mid]) high = mid - 1; else low = mid + 1; } for(int j=i-1; j>=low; j--) nums[j+1] = nums[j]; nums[low] = temp; } } return nums; } //希尔排序。每次步长逐渐减小,直至为1.不稳定的算法 public static int[] shellSort(int[] nums) { if(nums == null || nums.length == 0 || nums.length == 1) return nums; int i, j, gap = nums.length; int temp = 0; do { gap = gap / 3 + 1; for(i=gap; i<nums.length; i++) { if(nums[i] < nums[i-gap]) { j = i - gap; temp = nums[i]; do { nums[j + gap] = nums[j]; j = j - gap; } while(j >= 0 && temp < nums[j]); nums[j+gap] = temp; } } } while(gap > 1); return nums; } //快速排序。采用分治法,每次选出一个pivot,使得数组左边的元素都比pivot小,数组右边的元素都比pivot大。 public static void quickSort(int[] nums, int left, int right) { if(left < right) { int pivotpos = partition(nums, left, right); quickSort(nums, left, pivotpos-1); quickSort(nums, pivotpos+1, right); } } public static int partition(int[] nums, int left, int right) { int pivotpos = left, pivot = nums[left]; for(int i=left+1; i<=right; i++) { if(nums[i] < pivot) { pivotpos++; if(pivotpos != i) { int temp = nums[i]; nums[i] = nums[pivotpos]; nums[pivotpos] = temp; } } } nums[left] = nums[pivotpos]; nums[pivotpos] = pivot; return pivotpos; }