Please Tell me my mistake in this program

c-plus-plus

#1

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*;}
	QSort(0,4);
	cout<<"Sorted Elements are : "<<endl;
	for(i=0;i<5;i++)
		cout<<a*;
	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;      
}

#2

> but it is taking infinite

while(true)
{
...

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


#3

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


#4

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


#5

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.


#6

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


#7

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


#8

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.


#9

because we were instructed to implement without using that function.


#10

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:


#11

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