首页 > 代码库 > [算法总结]partition (quicksort)

[算法总结]partition (quicksort)

private int partition(int[] nums, int lo, int hi) {
        if (lo >= hi) {
            return lo;
        }
        int i = lo;
        int j = hi + 1;
        int v = nums[lo];
        while (true) {
            while (nums[++i] < v)
                if (i == hi) break;
            while (nums[--j] > v)
                if (j == lo) break;
            if (i >= j) {
                break;
            }
            int tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }
        nums[lo] = nums[j];
        nums[j] = v;
        return j;
    }

lo和hi都是inclusive的。 返回的数组中,index小于j的数都小于等于j,index大于j的数都大于等于j

[算法总结]partition (quicksort)