简体   繁体   中英

Two questions about quicksort

I have two questions when learning quicksort currently. The standard code is here(copy from my book):

void Quicksort(int a[], int low, int high){
    if(low<high){
      int pivotpos=Patrition(a,low,high);
      Quicksort(a,low,pivotpos-1);
      Quicksort(a,pivotpos+1,high);
    }
}
int Patrition(int a[], int low, int high){
    int pivot=a[low];  //first elemnent as pivot
    while(low<high){
        while(low<high&&a[high]>=pivot) --high;   //1
        a[low]=a[high];
        while(low<high&&a[low]<=pivot)  ++low;    //2
        a[high]=a[low];
   }
    a[low]=pivot;
    return low;     
}

My questions are in the above code(marked 1 and 2):

a. why the program cannot be performed(core dumped) when I type this in 1: while(a[high]>=pivot) --high (similarly in 2). It seems that I have to add the condition(low<high) in the second and third while loop or it said core dumped?

b. another question is why there must be a operator= in second and third while loop. I am confused why it won't work when I type while(low<high&& a[high]>pivot (similarly in 2). If I do so, this program will keep looping and never goes to end.

Thanks for your attention. Any suggestion will be highly appreciated.

The reason for having to write low < high in each while-loop is because it first checks the condition for the first while (the big one), starts looping, then it check the condition in while //1 and keeps looping, but during that time, the first while's (the big one) condition is never checked.

Example:

a = 6;

while (a > 5) {
    while (a > 3) {
         --a;
    }
}

In this code, the second loop only stops when a = 3.

As for question b, it's because it never actually reaches the value that needs to be changed, hence never actually sorting it.

Example: If you'd want the loop to stop at a = 3, the following loop would stop one step earlier.

a = 5;
while (a > 4) {
     --a;
}

Value a never reaches 3, it stops at a = 4,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM