Learning quicksort should not be the first thing you program. Understanding how quicksort works (and more importantly,
why it works so well) is pretty complicated.
Judging by your other post, it sounds you aren't quite sure how any type of sorting works, let alone quicksort.
Before you get overwhelmed by the concept of sorting, you should break things down into smaller parts.
Let's look at this array, {1, 2, 4, 3, 5}. It is not sorted, because 3 > 4, but the 3 comes after 4.
What would you do to sort this? You would simply swap the 3 and of 4.
Do you know how to swap two elements in an array?
scroll down to the bottom of this page for an example of vector
http://en.cppreference.com/w/cpp/container/vector
Here's my example mentioned above, in code
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
|
// Example program
#include <iostream>
#include <vector>
#include <algorithm> // swap
int main()
{
std::vector<int> vec = {1, 2, 4, 3, 5};
// vec[0] is 1
// vec[1] is 2
// vec[2] is 4 <-- out of order
// vec[3] is 3 <-- out of order
// vec[4] is 5
// We want to swap the 4 and 3
std::swap(vec[2], vec[3]);
// Now, the vector is sorted. Print out out to see for yourself.
for (int element : vec)
{
std::cout << element << " ";
}
}
|
Now, think about what would happen if multiple pairs of elements are out of order, and not just the {4, 3}?
For example, {4, 1, 5, 2}.
We look through each element, starting at the first one, and looking at consecutive elements. If the next element is smaller than the previous element, we know that we need to do some swapping. Otherwise, if every previous element is smaller than the next element, the array is sorted.
In the example, we start at the beginning of the array, and we see that 1 is less than 4, so we swap 4 and 1.
The array is now {1, 4, 5 2}.
Then, start at the beginning of the array, and iterate up until we see that 2 is less than 5, so let's swap the 5 and 2.
The array is now {1, 4, 2, 5}.
Then, start at the beginning of the array, and iterate up until we see that 2 is less than 4, so leet's swap the 4 and 2.
The array is now {1, 2, 4, 5}.
Finally, start at the beginning of the array, and iterate up, and we will see that every element is not decreasing. The array is sorted.
Note: What I am describing above is not quicksort, but rather a more naive algorithm. But you should understand the simpler algorithms before you conquer quicksort.
But as Andy said, there are plenty of code and pseudo-code examples of quicksort, and other simpler sorting algorithms. Just google "C++ quicksort" if you need to.