java--快速排序

52 篇文章 0 订阅
19 篇文章 0 订阅
本文介绍了快速排序算法,这是一种基于分治思想的交换排序。通过双边循环法和单边循环法展示了如何实现快速排序,其中partition函数是关键。文中还提供了详细的代码示例和调试过程,帮助理解算法的运作原理。
摘要由CSDN通过智能技术生成

什么是快速排序?

排序动画演示网站

属于交换排序的一种,利用了分治的思想,将序列根据 pivot (中间值) 划分为两个序列,在 pivot 左边的元素全部都比 pivot 值小,在右边的比 pivot 大,对子序列递归操作。

双边循环法demo

递归,利用辅助函数确定 pivot 的索引并排序。

package sort;

/**
 * @Description: TODO
 * @author: HardyDragon
 * @date: 2021年07月07日 14:01
 */
public class QuickSort {
    public void quickSort(int[] arr, int startIndex, int endIndex) {
        if (startIndex >= endIndex) {
            return;
        }
        int pivotIndex = partition(arr, startIndex, endIndex);
        quickSort(arr, startIndex, pivotIndex - 1);
        quickSort(arr, pivotIndex + 1, endIndex);
    }

    private int partition(int[] arr, int startIndex, int endIndex) {
        int pivot = arr[startIndex];
        int left = startIndex;
        int right = endIndex;

        // 当pivot在左端时,从right先开始移动,重合点是比pivot小的值,反之。
        while (left != right) {
            // right向左移,找比pivot小的然后停下
            while (left < right && arr[right] > pivot) {
                right--;
            }
            // left 向右移,找到比pivot 大的停下
            while (left < right && arr[left] <= pivot) {
                left++;
            }

            // 交换left
            if (left < right) {
                int temp = arr[left];
                arr[left] = arr[right];
                arr[right] = temp;
            }
        }
        
        // 交换pivot和指针重合点
        arr[startIndex] = arr[left];
        arr[left] = pivot;

        return left;
    }
}

调试

package sort;

public class Main {
    public static void main(String[] args) {
        int[] nums = {45, 29, 40, 25, 98, 77, 46, 20, 21, 97};
        QuickSort quickSort = new QuickSort();
        quickSort.quickSort(nums, 0, nums.length - 1);
        for (int num : nums) {
            System.out.print(num + " ");
        }
    }
}
20 21 25 29 40 45 46 77 97 98 

单边循环法

只是 partition() 函数部分不同。

从pivot 后一个元素开始遍历,mark 以前的元素都比pivot小,最后将pivot和mark交换。

private int partition2(int[] arr, int startIndex, int endIndex) {
    int pivot = arr[startIndex];
    int mark = startIndex;

    for (int i = startIndex + 1; i <= endIndex; i++) {
        if (arr[i] < pivot) {
            mark++;
            int temp = arr[mark];
            arr[mark] = arr[i];
            arr[i] = temp;
        }
    }
    arr[startIndex] = arr[mark];
    arr[mark] = pivot;
    return mark;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值