Implementation of Quick Sort

妖精的绣舞 提交于 2019-12-12 04:35:55

问题


#include<stdio.h>
#include<iostream.h>
#include<conio.h>

void quicks(int *arr,int x,int pivot,int lo,int hi);
void swap1(int *x,int *y);
int main()
{
int *arr = new int[7];
arr[0] = 23;
arr[1] = 3;
arr[2] = -23;
arr[3] = 45;
arr[4] = 12;
arr[5] = 76;
arr[6] = -65;
quicks(arr,7,0,1,6);
for(int i = 0;i<7;i++)
    std::cout << arr[i] <<"\t";
getch();
return 0;
 }
 void quicks(int *arr,int x,int pivot,int lo,int hi)
 {
int i = lo,j = hi;
if(pivot < x-1)
{
while(i <= hi)
{
    if(arr[i] <= arr[pivot])
        i++;
    else
        break;
}
while(j >= lo)
{
    if(arr[j] >= arr[pivot])
        j--;
    else    
        break;
}
if( i > j)
{
    swap1(&arr[j],&arr[pivot]);
    lo = pivot+1;
    hi = x - 1;
    quicks(arr,x,pivot,lo,hi);
}
else if(i == j)
{
    pivot = pivot + 1;
    lo = pivot+1;
    hi = x - 1;
    quicks(arr,x,pivot,lo,hi);
}
else if(i < j)
{
    swap1(&arr[j],&arr[i]);
    lo = i + 1;
    hi = j - 1;
    quicks(arr,x,pivot,lo,hi);
}
}
else
{
    printf("\nDONE\n");
}
}

void swap1(int *x,int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}

Hi, I have written a program to implement Quick sort.But the program is going into an infinite loop.In the Quicks function,the while loops for incrementing and decrementing i and j are the problem.Can anybody tell me what is wrong with this Implementation of QUick Sort.


回答1:


Do a quick dry run using your input and the algorithm, you'll notice you run into an infinite cycle after a while.

You are starting the loop from quicks(arr,7,0,1,6);. Try instead by setting low to the "rightmost" element, that is 0. This won't definitely solve your problem as the algorithm seems really flawed, with the position of high not changing at all, and i moving all the way to high. You're trying to complicate a very simple task.

i would go from lo to pivot. And j from hi to pivot. After the pivot is found to be in the right place, you'll move forward pivot and lo by 1, and repeat the process.

Take a look at this image, you'll get an idea of the algo required:



来源:https://stackoverflow.com/questions/13394014/implementation-of-quick-sort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!