Advertisement

Quick Sort (C++)

Started by February 26, 2003 11:35 AM
0 comments, last by JohnTrent 21 years, 8 months ago
How well does this work as a quicksort (I''m using a special vector class provided in my course) apvector quickSort(apvector file) { if(file.length() <= 1)return file; apvector l(file.length()-1), r(file.length()-1); apvector mid(1,file[0]); // creates a vector of length 1 consisting of position 0 int f = file[0], lC=0, rC=0; for(int x = 1; x < file.length(); x++) { if(file[x] <= f) { l[lC] = file[x]; lC++; } else { r[rC] = file[x]; rC++; } } l.resize(lC); r.resize(rC); return quickSort(l) + mid + quickSort(r); }
This doesn''t really look like a good quicksort, for two reasons:

1. Your pivot selection - you are selecting the first element of the vector for each iteration, which means that if the vector is already sorted, nearly sorted, or sorted backwards you will get O(n^2) running time. Random selection or median of three (or a combination of both) would be better.

2. You are copying the vector into two rectors (r and l) which defeats the purpose of a quicksort. If you are going to copy vectors you may as well use a mergesort, which would be faster. The point of a quicksort is that you don''t need to copy vectors like you do with a mergesort, thus cutting down on the constant running time of each iteration.
-YoshiXGXCX ''99

This topic is closed to new replies.

Advertisement