Hello,
My code works but I would like to adjust it to perform better. My teacher would like me to perform quickSort with pointers. I did use them but I was wondering what else I could change to improve the usage of pointers? For instance how can I pass pointers to the partition function?
My code is below:
void Sort::swap(int &value1, int &value2)
{
int temp = value1;
value1 = value2;
value2 = temp;
}
int Sort::partition(int set[], int start, int end)
{
int currentValue, pivot, mid;
mid = (start + end) / 2;
swap(set[start], set[mid]);
pivot = start;
currentValue = set[start];
for (int scan = start + 1; scan <= end; scan++)
{
if (set[scan] < currentValue)
{
pivot++;
swap(set[pivot], set[scan]);
}
}
swap(set[start], set[pivot]);
return pivot;
}
void Sort::quickSort(int set[], int start, int end)
{
int pivotPoint;
if (start < end)
{
// Get the pivot point.
pivotPoint = partition(set, start, end);
// Sort the first sub list.
quickSort(set, start, pivotPoint - 1);
// Sort the second sub list.
quickSort(set, pivotPoint + 1, end);
}
}
bool Sort::test()
{
Sort set; // create object
bool answer = false;
cout << "Enter the size of the array: ";
//cin >> arraySize;
cout << "50";
set.arraySize = 50;
cout << "\nArray being randomly populated with integers.";
// pointers add/change values in the array indirectly
int *prt1=new int[set.arraySize];
// randomize the random number generator for the array elements using current time
srand ( (unsigned)time ( 0 ) );
//insert random numbers into the array
for (int i=0; i < set.arraySize; i++)
*(prt1 + i)= 1 + rand() % 1000;
//print the numbers in the array before sorting
cout << "\n\nThe integers before sorting are:\n";
for (int i=0; i < set.arraySize; i++)
cout << *(prt1 + i) << "\t";
set.quickSort(prt1, 0, set.arraySize-1);
//now print the sorted numbers
cout << "\n\nThe integers after sorting are: \n";
for(int i=0; i < set.arraySize; i++)
cout << *(prt1 + i) << "\t";
// test the values to see if the program was successful
if(*(prt1 + 1) < *(prt1 + 2))
{
answer = true;
}
return answer;
}