Question 10. Sorting II [9]
The program below implements the labex5 partitioning algorithm and runs it once on a small array, but printing the array contents repeatedly as it works through the array.
Show the output the program produces.
#include <iostream>
using namespace std;
void swap(float &a, float &b)
{
float t = a;
a = b;
b = t;
}
void printArr(float arr[], int lower, int upper)
{
for (int i = lower; i <= upper; i++) {
cout << arr[i] << ",";
}
cout << endl;
}
int partition(float arr[], int lower, int upper)
{
if (upper <= lower) return lower;
float pivotVal = arr[lower];
swap(arr[lower], arr[upper]);
int pos, midpt;
midpt = lower;
for (pos = lower; pos < upper; pos++) {
if (arr[pos] < pivotVal) {
swap(arr[pos], arr[midpt]);
midpt++;
}
cout << pos << ": ";
printArr(arr, lower, upper);
}
swap(arr[midpt], arr[upper]);
return midpt;
}
int main()
{
float arr[] = { 10, 5, 12, 4, 3, 6, 15 };
partition(arr, 0, 6);
}
|