Search code examples
javaquicksortpartition

Failed partitioning for quicksort in java


I know there are a lot on quicksort but I'm only using it to learn how to code algorithms, and from what you can see I obviously can't.


    public static int[] partition(int [] arr, int startNumber, int endNumber) {
        
        //highIndex is the second last element, lowIndex the first, pivot the last.
        
        int highIndex = endNumber -2;
        int pivot = arr [endNumber -1];
        int lowIndex = startNumber;
        
        
        // I don't want the loop to initiate when the element from the left aligns with the element from the right
        // thus it should stop when arr[highIndex] equals arr[lowIndex].
        while (highIndex > lowIndex) {
            
            
            // the index increases as we go from the left to right without the element being greater than the pivot
            // or the index equal or greater to the index from the right
            while (arr[lowIndex] <= pivot && highIndex > lowIndex) {
                lowIndex++;
            }
            
            while (arr[highIndex] > pivot && highIndex > lowIndex) {
                highIndex--;
            }
            
            // interchanging the elements which are greater and less than the pivot. 
            
             int temp = arr[highIndex];
             arr[highIndex] = arr[lowIndex];
             arr[lowIndex] = temp;
            
        }
        
        //changing the pivot with the element arr[highIndex]. But arr[highIndex] should be equal to arr[lowIndex]
        // at this point so it shouldn't matter if I'm changing with low or high. 
        int temp2= arr[highIndex];
        pivot = arr[highIndex];
        arr[highIndex] = temp2;
    
        
        return arr;
        
        
    }
    
    public static void main(String[] args) {
        
        int [] arr2 = {21, 24, 13, 25, 27, 5, 2, 20, 6, 23};  
        
        System.out.println( Arrays.toString(arr2));
        
        partition(arr2,0, arr2.length);
        
        System.out.println(Arrays.toString(arr2));
        
    }


This code generates: [21, 24, 13, 25, 27, 5, 2, 20, 6, 23] [21, 6, 13, 20, 2, 27, 5, 25, 24, 23]

The pivot has not changed spot. I'm trying to get it partitioned with 23 as the pivot.


Solution

  • There are at least 1 problem with your code:

    • In the final part, external to the main while (highIndex > lowIndex), when you think that you replace the pivot, actually you don't but you assign to the temp2 and pivot variables the content in arr[highIndex] and after you assign to arr[highIndex] = temp2 (itself). I believe it's a careless mistake and the right code is:

        int temp2= arr[highIndex];
        arr[highIndex] = pivot;
        arr[endNumber-1] = temp2;
      

    After this fix you need to implement the last part of the algorithm.