• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Help w/ Quick Sort in C++

PCMarine

Diamond Member
I have been assigned to construct a C++ program which uses the Quicksort to sort a 20 element array. Then the program will output the original array, and the array after one pivot. Now I think im very close to getting it right, but I can't seem to figure what else I have to do. Hopefully some of you can help me out 😉

// Quick Sort

#include <iostream.h>
#include <iomanip.h>

void output_orig(int list[]);
void quickSort(int list[], int left, int right, int pivot);
void output_pivot(int list[]);

int main()
{
int list[21] = {51, 46, 4, 70, 2, 42, 53, 16, 7, 3, 50, 67, 41, 2, 45, 34, 8, 19, 13, 3};
int left = 0;
int right = 19;
int pivot = (19 + 1) / 2;

output_orig(list);
quickSort(list, left, right, pivot);
return 0;
}

void output_orig(int list[])
{
int a = 0;
cout << "The Original Array is : ";
for (a = 0; a <= 19; a++)
{
cout << setw(4) << list[a];
}
cout << endl;
cout << endl;
}

void quickSort(int list[], int left, int right, int pivot)
{
int temp = 1;
do
{
if (list
> list[pivot])
{
do
{
if (list
< list[pivot])
{
temp = list
;
list
= list
;
list
= temp;
right++;
temp = 0;
}
else if(list
> list[pivot])
{
right--;
}
}
while(temp != 0);
temp = 1;
left++;
}
}
while (left > pivot);
output_pivot(list);
}

void output_pivot(int list[])
{
int b = 0;
cout << "The Partially Sorted Array is : ";
for (b = 0; b <= 19; b++)
{
cout << setw(4) << list;
}
cout << endl;
}
 
Just do it like a partition. Pick your pivot and then scan from the left till you got something >= and then scan from the right until you got something < (while left < right obviously). Do the switch.
 
Back
Top