change pivot in my quickSort algorithm java

后端 未结 3 1773
野性不改
野性不改 2021-01-26 13:01

I have implemented a working quickSort algorithm using the first element in the array as the pivot, that look like this:

public int[] quickSort( int[] a, int st         


        
3条回答
  •  抹茶落季
    2021-01-26 13:23

    If you choose to start with pivoting on an arbitrary element you have to change the behavior of your partitioning loop. See the code below:

    /* Selecting the pivot to be a random-ish element
       and pivotIndex to be beginning, since we don't know
       where it will be until we loop through the list */
    int pivot = a[someInt];
    int pivotIndex = begin-1;
    //have to keep track of where the pivot actually is in the list
    int currentPivotIndex = someInt;
    
    for(int i = begin; i <= end; i++) {
        if(a[i] <= pivot) {
            //for each element less than the pivot
            //the pivotIndex moves by one
            pivotIndex++;
            //place the element to the left of the pivot
            this.swap(a, pivotIndex, i);
            //update currentPivotIndex if needed
            if(a[pivotIndex] == pivot) {
                currentPivotIndex = pivotIndex;
            }
        }
    }
    //put the pivot in its place
    this.swap(a, pivotIndex, currentPivotIndex);
    

提交回复
热议问题