Please Tell me my mistake in this program

I’ve made this program as the demonstration of Quick Sort.
I’ve defined it for 5 inputs but it is taking infinite.
please tell me the Mistake in it.

#include<iostream>
using namespace std;
int a[5];
void QSort(int,int);
int Divide(int,int);
int main()
{
	int i;
	cout<<"Enter Elements : "<<endl;
	for(i=0;i<5;i++)
		{cin>>a[i];}
	QSort(0,4);
	cout<<"Sorted Elements are : "<<endl;
	for(i=0;i<5;i++)
		cout<<a[i];
	return 0;
}
void QSort(int first,int last)
{
        if(first<last)
        {
                int index=Divide(first,last);
                QSort(first,index-1);
                QSort(index+1,last);
        }
}
int Divide(int f,int l)
{
        int pivot=a[f];
        int left=f+1;
        int right=l;
        while(true)
        {
                while((a<=pivot)&&(left<right))
                        left++;
                while((a[right]>=pivot)&&(right>left))
                        right--;
                if(left<right)
                {
                        int temp=a;
                        a=a[right];
                        a[right]=temp;
                }
        }
        int temp=a;
        a=a[f];
        a[f]=temp;
        return left;      
}

> but it is taking infinite

while(true)
{
...

of course, as your while loop never ends ! :slight_smile:

3 Likes

you have define int a[5] outside the main function.

Remove the while(true) condition with the correct condition and you’re good to go ! :slight_smile:

the program is not taking input infinite times. the program enters into a infinite loop inside the while() loop in the function Divide() because there is no terminating condition in that loop.
add a terminating condition inside the while() loop so that the program an terminate.

You have used an infinite loop…while(true) instead of true place the correct condition for loop termination

any reason for not using the qsort() function in standard library ?

But while taking input, it should not me redirected to the while loop.
it should be in main function only.
because i am not calling any function there.

because we were instructed to implement without using that function.

But you call QSort() in the main() , and in qsort function you call Divide, so it’ll start an loop
while(true) without any break inside,
and it won’s finish :wink:

does that really matter? I’ll show you codes where i declare array of size upto 10^6 outside main funtion which called as global declaration in programming languages

1 Like