1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
#include <iostream>
#include <vector>
using namespace std;
// ===== YOUR CODE - WITH INSTRUCTED AMENDMENTS - FROM AN EARLIER POST
static void QuickSortHelper(vector<double>& vec1, size_t from, size_t to)
{
if ( to <= from ) return; // <===== KEY: BASE CASE TO END RECURSION
size_t i = from; // <===== get the type correct
size_t j = to; // <===== get the type correct
// <===== remove size
double tmp; double pivot = vec1[(i + j) / 2];
while (i < j) { // <===== less than, not <=
while (vec1[i] < pivot)
i++;
while (vec1[j] > pivot)
j--;
if (i < j) {
tmp = vec1[i];
vec1[i] = vec1[j];
vec1[j] = tmp;
i++;
j--;
}
};
QuickSortHelper( vec1, from, j ); // <===== KEY: REPLACE WITH RECURSIVE SORT
QuickSortHelper( vec1, j+1, to ); // OF ADJACENT PARTITIONS
}
vector<double> QuickSort(vector<double>& vec1) {
vector<double> result(vec1);
if (vec1.size()<=1) { // <===== minor amendment
return vec1;
}
else {
QuickSortHelper(result, 0, result.size() - 1);
}
return result;
}
// ===== END OF YOUR CODE (AMENDED) ===============================================
// === Added for testing ...
void write( const vector<double> &V )
{
for ( double e : V ) cout << e << " ";
cout << '\n';
}
//======================================================================
int main()
{
vector<double> A = { 1, 2, 3, 4, 5 };
vector<double> B = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
vector<double> C = { 1, 5, 6, 4, 9, 2, -3, 7 };
vector<double> D = { 5, 5, 5, 5, 5, 5, 5 };
A = QuickSort( A ); write( A );
B = QuickSort( B ); write( B );
C = QuickSort( C ); write( C );
D = QuickSort( D ); write( D );
}
|