目录
实现快速排序【QuickSort】并提供升序和降序方法
public class QuickSort {
// 排序方式:升序
private static final int UP_SORT_TYPE = 1;
// 排序方式:降序
private static final int DOWN_SORT_TYPE = -1;
/**
* 升序排列
*
* @param nums:要排序的数组
*/
public static void upSort(int[] nums) {
if (nums == null || nums.length < 2)
return;
sort(nums, 0, nums.length - 1, UP_SORT_TYPE);
}
/**
* 降序排列
*
* @param nums:要排序的数组
*/
public static void downSort(int[] nums) {
if (nums == null || nums.length < 2)
return;
sort(nums, 0, nums.length - 1, DOWN_SORT_TYPE);
}
/**
* 实现排序
*
* @param nums:要排序的数组
* @param low:最左下标
* @param high:最右下标
* @param sortType:排序方式
*/
private static void sort(int[] nums, int low, int high, int sortType) {
if (low < high) {
int partitionIndex = partition(nums, low, high, sortType);
sort(nums, low, partitionIndex - 1, sortType);
sort(nums, partitionIndex + 1, high, sortType);
}
}
private static int partition(int[] nums, int low, int high, int sortType) {
// 找一个支点,这里支点我选择用low
int pivot = nums[low];
while (low < high) {
// 根据不同的排序规则
if (sortType == UP_SORT_TYPE) {
// 处理升序
while (low < high && nums[high] >= pivot) {
high--;
}
nums[low] = nums[high];
while (low < high && nums[low] <= pivot) {
low++;
}
} else {
// 处理降序
while (low < high && nums[high] <= pivot) {
high--;
}
nums[low] = nums[high];
while (low < high && nums[low] >= pivot) {
low++;
}
}
nums[high] = nums[low];
}
// 这里用的是low,用high也一样,此时low==high
nums[low] = pivot;
return low;
}
}
快速排序方法测试
import java.util.Arrays;
public class QuickSortTest {
public static void main(String[] args) {
// 测试升序
int[] nums1 = {23, 12, 34, 42, 345, 56, 45, 34, 37, 43, 1, 23, 44, 67};
QuickSort.upSort(nums1);
// [1, 12, 23, 23, 34, 34, 37, 42, 43, 44, 45, 56, 67, 345]
System.out.println(Arrays.toString(nums1));
// 测试降序
int[] nums2 = {23, 12, 34, 42, 345, 56, 45, 34, 37, 43, 1, 23, 44, 67};
QuickSort.downSort(nums2);
// [345, 67, 56, 45, 44, 43, 42, 37, 34, 34, 23, 23, 12, 1]
System.out.println(Arrays.toString(nums2));
}
}