快速排序算法

快速排序

指定首元素为pivot

public class QuickSort2 {
    public static void quickSort(int[] nums, int startIndex, int endIndex) {
        if (startIndex >= endIndex) {
            return;
        }
        int pivot = partition2(nums, startIndex, nums.length - 1);
        quickSort(nums, startIndex, pivot - 1);
        quickSort(nums, pivot + 1, endIndex);
    }

    /**
     * 双端遍历
     */
    public static int partition(int[] nums, int startIndex, int endIndex) {
        int left = startIndex;
        int right = endIndex;
        int pivot = nums[startIndex];

        while (left != right) {
            while (left < right && nums[right] >= pivot) {
                right--;
            }
            while (left < right && nums[left] <= pivot) {
                left++;
            }
            if (left < right) {
                int temp = nums[right];
                nums[right] = nums[left];
                nums[left] = temp;
            }
        }

        nums[startIndex] = nums[left];
        nums[left] = pivot;
        return left;
    }

    /**
     * 单端遍历
     */
    public static int partition2(int[] nums, int startIndex, int endIndex) {
        int mark = startIndex;
        int pivot = nums[startIndex];

        for (int i = startIndex + 1; i <= endIndex; i++) {
            if (nums[i] < pivot) {
                mark++;
                int temp = nums[mark];
                nums[mark] = nums[i];
                nums[i] = temp;
            }
        }
        int temp = nums[mark];
        nums[mark] = pivot;
        nums[startIndex] = temp;
        return mark;
    }

    public static void main(String[] args) {
        int[] nums = {1, 3, 2, 5, 6, 4, 3, 9, 8, 0,2,3,6,5};
        quickSort(nums, 0 , nums.length - 1);
        System.out.println(Arrays.toString(nums));
    }
}

双端遍历

  1. 遍历尾指针,直到遇到小于pivot的值停下
  2. 遍历头指针,直到遇到大于pivot的值停下
  3. 交换头尾指针的值
  4. 重复上面三个步骤直到头尾指针相等
  5. 交换pivot和头指针的值

单端遍历

  1. 从pivot下一个元素开始遍历,遇到小于pivot值时
    1. mark指针右移一位
    2. 交换mark指针和当前指针的值
  2. 遍历结束后,交换pivot和mark指针的值
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值