Sort

Quick Sort

    private 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);
    }
    
    // set the select num in the correct position in nums
    // return the index of the selected num
    private int partition(int[] nums, int start, int end){
        int ran = (int) (Math.random()*(end - start + 1) + start);
        swap(nums, ran, end);
        
        int left = start;
        int right = end-1;
        while(left<=right){
            if(nums[left]>nums[end]){
                swap(nums, left, right);
                right--;
            }else{
                left++;
            }
        }
        // put the pivot to the correct position;
        swap(nums, left, end);
        // index of left now is the index of pivot
        return left;
    }
    
    private void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

merge sort

Last updated

Was this helpful?