c++ - Quicksort correct implemetation but with some extra comparisons -
i'm trying pull maximum out of quicksort implementation. functionally correct , has canonical form, i've counted superfluous comparisons. use first element pivot:
#include <vector> using namespace std; using uint = unsigned int; uint partitionsub(vector<uint>& inp, uint l, uint r, uint& numofcmp); void quicksort(vector<uint>& inp, uint l, uint r, uint& numofcmp) { if (r - l < 2) return; uint newpivotidx = partitionsub(inp, l, r, numofcmp); quicksort(inp, l, newpivotidx, numofcmp); quicksort(inp, newpivotidx + 1, r, numofcmp); } uint partitionsub(vector<uint>& inp, uint l, uint r, uint& numofcmp) { auto swap = [&inp](uint a, uint b) { uint buf = inp[a]; inp[a] = inp[b]; inp[b] = buf; }; //numofcmp += r - l; // can use this, ++numofcmp before // comparison more clear uint = l + 1; uint j = l + 1; uint p = inp[l]; (; j <= r; j++) { ++numofcmp; if (inp[j] < p) { if (i != j) swap(i, j); i++; } } uint newpivotidx = - 1; swap(l, newpivotidx); return newpivotidx; }
given input: 3,9,8,4,6,10,2,5,7,1 25 comparisons required, 27. i've been debugging 3 days , have no clues. if guys see places should optimized in sense of making fewer comparisons, please give me directions? understand, it's due redundant recursion pass, since partition subroutine , counting in implemented correctly.
i may have spotted problem:
quicksort(inp, l, newpivotidx, numofcmp); quicksort(inp, newpivotidx + 1, r, numofcmp);
you don't need include pivot element in recursion; know it's in correct position. change first line
quicksort(inp, l, newpivotidx-1, numofcmp);
you haven't displayed debugging output, such trace of printing arguments on function entry, , i'm afraid don't have time myself right now. hope happens problem.
Comments
Post a Comment