算法练习-快速排序

定义

是对冒泡排序的改进
通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。

实现步骤

  1. 定基准——首先随机选择一个元素最为基准
  2. 划分区——所有比基准小的元素置于基准左侧,比基准大的元素置于右侧
  3. 递归调用——递归地调用此切分过程

复杂度

时间复杂度根据中位pivot的选择情况而定,平均是O(NlogN),但是如果pivot选择的极端情况,最差为O(N*N)
控件复杂度:O(1)

和归并算法的区别

归并排序将数组分成两个子数组分别排序,并将有序的子数组归并以将整个数组排序。递归调用发生在处理整个数组之前。
快速排序将一个数组分成两个子数组并对这两个子数组独立地排序,两个子数组有序时整个数组也就有序了。递归调用发生在处理整个数组之后。

代码

public class QuickSort {

    public static void quick(int[] arr) {
        quick(arr, 0, arr.length - 1);
    }

    private static void quick(int[] arr, int low, int high) {
        if (low < high) {
            int mid = quickSort(arr, low, high);
            quick(arr, low, mid);
            quick(arr, mid + 1, high);
        }
    }

    public static int quickSort(int[] arr, int low, int high) {
        int result = arr[low];
        int i = low, j = high;
        while (i < j) {
            while (i < j && result <= arr[j]) {
                j--;
            }
            if (i < j) {
                arr[i] = arr[j];
            }
            while (i < j && result >= arr[i]) {
                i++;
            }
            if (i < j) {
                arr[j] = arr[i];
            }
        }

        arr[i] = result;
        return i;
    }

}

单元测试代码

public class test extends TestCase {

    int[] helper = { 7, 3, 2, 10, 5, 2, 6, 8 };
    int[] helperQuick = helper.clone();
    int[] correct = { 2, 2, 3, 5, 6, 7, 8, 10 };

    public void testMergeIntArray() {
        MergeSort.merge(helper);
        for (int i = 0; i < helper.length; i++) {
            assertEquals(helper[i], correct[i]);
        }
    }

    public void test_quickSort() {
        int index = QuickSort.quickSort(helper, 0, helper.length - 1);
        assertEquals(index, 5);
    }

    public void test_quick() {
        QuickSort.quick(helperQuick);
        for (int i = 0; i < helperQuick.length; i++) {
            assertEquals(helperQuick[i], correct[i]);
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值