快排
public void quickSort(int[] nums, int low, int high) {
System.out.println(low + " " + high);
if(low < high) {
int i = partition(nums, low, high);
System.out.println(i);
quickSort(nums, low, i - 1);
quickSort(nums, i + 1, high);
}
}
public int partition(int[] nums, int low, int high) {
int temp = nums[low];
while(low < high) {
while(low < high && nums[high] >= temp) {
high--;
}
nums[low] = nums[high];
while(low < high && nums[low] <= temp) {
low++;
}
nums[high] = nums[low];
}
nums[low] = temp;
return low;
}
堆排序
public void heapSort(int[] nums) {
buildMaxHeap(nums, nums.length);
for(int i = nums.length - 1; i > 0; i--) {
swap(nums, 0, i);
buildMaxHeap(nums, i);
}
}
public void buildMaxHeap(int[] nums, int length) {
// 从最后一个非叶子节点依次往前进行遍历
for(int i = length/2 - 1; i >= 0; i--) {
adjustDown(nums, i, length);
}
}
public void adjustDown(int[] nums, int i, int length) {
int temp = nums[i];
for(int j = i * 2 + 1; j < length; j = j * 2 + 1) {
if(j + 1 < length && nums[j] < nums[j+1]) {
j++;
}
if(temp < nums[j]) {
nums[i] = nums[j];
i = j;
}else {
break;
}
}
nums[i] = temp;
}
public void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}