QuickSort(Java)

实现代码:

public class QuickSort {
    public void sort(int[] input) {
        quickSort(input, 0, input.length - 1);
    }

    private void quickSort(int[] input, int begin, int end) {
        if (begin >= end) return;
        int mid = partition(input, begin, end);
        quickSort(input, begin, mid-1);
        quickSort(input, mid+1, end);
    }

    private int partition(int[] input, int begin, int end) {
        int x = input[begin];
        int smallIndex = begin, bigIndex = begin;
        while(++bigIndex <= end) {
            if (input[bigIndex] >= x) continue;
            else {
                smallIndex++;
                swap(input, smallIndex, bigIndex);
            }            
        }
        swap(input, begin, smallIndex);
        return smallIndex;
    }

    private void swap(int[] input, int lhs, int rhs) {
        int temp = input[lhs];
        input[lhs] = input[rhs];
        input[rhs] = temp;
    }
}


测试代码:

import org.junit.*;

import static org.junit.Assert.assertArrayEquals;

public class QuickSortTest {
    private QuickSort quickSort;

    @Before
    public void setUp() {
        quickSort =  new QuickSort();
    }

    @Test
    public void should_return_1_for_quick_sort_1() {
        int[] input = {1};
        int[] expect = {1};
        quickSort.sort(input);
        assertArrayEquals(expect, input);
    }

    @Test
    public void should_return_12_for_quick_sort_21() {
        int[] input = {2, 1};
        int[] expect = {1, 2};
        quickSort.sort(input);
        assertArrayEquals(expect, input);
    }

    @Test
    public void should_return_1234_for_quick_sort_3124() {
        int[] input = {3, 1, 2, 4};
        int[] expect = {1, 2, 3, 4};
        quickSort.sort(input);
        assertArrayEquals(expect, input);
    }

    @Test
    public void should_return_12345678_for_quick_sort_46835217() {
        int[] input = {4, 6, 8, 3, 5, 2, 1, 7};
        int[] expect = {1, 2, 3, 4, 5, 6, 7, 8};
        quickSort.sort(input);
        assertArrayEquals(expect, input);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值