I have written a code for quick sort in c++ but it's giving an error for few inputs. For example : On Entering No. of elements = 5 with the inputs as 5 4 3 2 1
, it shows incorrect output for one iteration. It gives wrong output only on entering consecutive numbers in decreasing order.
#define MAX 100
class quicksort
{
public:
int arr[MAX], n;
void getdata();
void quick(int, int);
void display();
};
void quicksort::getdata()
{
int i;
cout << "\nEnter Array Size : ";
cin >> n;
cout << "\nEnter Array Elements : ";
for (i = 0; i < n; i++)
{
cout << "\nEnter Element [" << i << "] : ";
cin >> arr[i];
}
}
void quicksort::quick(int start, int end)
{
int pivot = start, i = pivot + 1, j = end, temp;
while (i <= j)
{
while (arr[i] < arr[pivot])
{
if (i == end - 1 || j <= i)
break;
i++;
}
while (arr[j] >= arr[pivot])
{
j--;
if (j < i)
break;
}
if (i < j)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
else
{
temp = arr[j];
arr[j] = arr[pivot];
arr[pivot] = temp;
}
if (j != start)
quick(start, j - 1);
if (j != end)
quick(j + 1, end);
}
}
int main()
{
quicksort s;
s.getdata();
s.quick(0, (s.n - 1));
s.display();
return 0;
}