Hey guys, I have a problem. I created a quick sort program and it functions perfectly for quantity less than 100. I searched for errors and changed and now for more than 100 values, it runs perfectly and sometimes it hangs. I am unable to decipher whats the error. Did i make any logical errors or not.
PLease note i am taking random values each and every time. So one set of numbers generated works and the other set does not (try values in the range of 700 or 800)
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
using namespace std;
class array
{
private:
int arr[3000];
int count;
public:
array();
void add( int item );
int getcount();
static int split(int*, int, int);
void quicksort(int lower, int upper);
void display();
};
array::array()
{
count = 0;
for(int i=0;i<3000;i++)
arr[i]=0;
}
void array::add(int item)
{
if(count<3000)
{
arr[count] = item;
count++;
//cout<<count<<endl;
}
else
cout<<"Array is full\n";
}
int array::getcount()
{
return count;
}
void array::quicksort(int lower, int upper)
{
if(upper > lower)
{
cout<<"\t"<<lower<<"\t"<<upper<<"\n";
int i=split(arr,lower,upper);
quicksort(lower, i-1);
quicksort(i+1,upper);
}
}
int array::split(int* arr, int lower, int upper)
{
int pivot,i,j,temp,i1,j1;
pivot=arr[lower];
i=lower+1;
j=upper;
i1=i;
j1=j;
while(i<j && i<=j1 && j>=i1)
{
while(pivot>arr[i])
{
i++;
}
while(pivot<arr[j])
{
j--;
}
if(j>i)
{
temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
else
{
continue;
}
}
if(j<=i)
{
temp = arr[lower];
arr[lower] = arr[j];
arr[j]=temp;
}
return j;
}
void array::display()
{
cout<<endl;
for(int i=0;i<count;i++)
cout<<arr[i]<<"\t";
}
int main()
{
array obj1;
srand(time(NULL));
cout<<"Enter the number of elements"<<endl;
int isize,temp;
cin>>isize;
for(int i=0;i<isize;i++)
{
temp = rand() % 10000 ; // values from 1000 t0 10999
//arr[i] = temp;
obj1.add(temp);
}
int top = obj1.getcount();
obj1.quicksort(0,top-1);
obj1.display();
return 0;
}