6. Quick Sort

thought

Quick sort, is to select an element and then through the exchange elements, selected elements are left to ensure that it is smaller than the right elements are greater than it. After each operation, the position of the position of the element is the sort selected.

Like more than one person height permutations as you read down, in front of people than you short, the people behind taller than you, then you can not move, how they toss with, anyway, where you stand on and they sort well, you still stand in this position.

achieve

import java.util.Arrays;

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

    }

    public static void quickSort(int[] nums, int start, int end){
        if(start>=end) return ;
        int mid = partition(nums, start, end);
        quickSort(nums, start, mid-1);
        quickSort(nums, mid+1, end);
    }

    public static int partition(int[] nums, int start, int end){
        
        int p_value = nums[start];
        int i = start, j = end+1;
        while(true){
            while(nums[++i]<p_value) if(i>=end) break;
            while(nums[--j]>p_value) if(j<=start) break;
            if(i>=j) break;
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
        int temp = nums[j];
        nums[j] = nums[start];
        nums[start] = temp;
        return j;
    }
}

the complexity

Quick drain of the average time complexity is NlogN. Space complexity is O (1)

Guess you like

Origin www.cnblogs.com/zhouzhiyao/p/12528452.html