Search code examples
javaarraysalgorithmsortingquicksort

Quick sort partition tweak


but I am trying to figure out how I can make so I may choose which ever pivot point I wish, Say for example on this list of integers, 8, 7, 1, 9 , 11, 5 , 6, I wished to choose say key 6 as the pivot point in my code. Or if I wanted to choose 9 or whatever. How could I write this into my code? Any help is much appreciated.

package quicksort;

public class quicky {
    private static void quicksort(int[] arr, int left, int right) {
        int index = partition(arr, left, right);
    
        if(left < index - 1)
            quicksort(arr, left, index - 1);
        if(index < right)
            quicksort(arr, index, right);
    }
    private static int partition (int[] arr, int left, int right) {
        int pivot = arr[(left + right) / 2];
        while(left<= right) {
            while(arr[left] < pivot) left++;
            while(arr[right]> pivot) right--;
        
            if(left<= right) {
                int tmp = arr[left];
                arr[left] =arr[right];
                arr[right] = tmp;
            
                left++;
                right--;
            }
        }
        return left;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int[] array = new int [] { 8, 7, 1, 9, 11, 5, 6};
        quicksort(array, 0 , array.length-1);
        for(int i = 0; i <array.length; i++)
            System.out.print(array[i]+ " ");        
        }        
    }
}

Solution

  • Simple method:

    1. Check if value exists in array.
    2. If it does, swap value with value in default pivot index.
    3. Proceed using same code/ lomuto partition.