Ben Duncan is right. The quicksort algorithm contains vectors but this is the fastest an understable algorithm I know so...I'll learn the vectors for it, if I am in your place.
Here I go:
This is the quicksort - function (you can implement it in main but is more clear this way).
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
|
void quicksort(int v[100], int left, int right)
{
int i, j, mid, aux;
i=left;
j=right;
mid=v[(left+right)/2]; // the initialization of the pivot - variable
while(i<=j)
{
while(v[i]<mid)
i++;
while(v[j]>mid)
j--;
if(i<=j) //the condition for the interchange operation
{
aux=v[i];
v[i]=v[j]; // the interchange operation
v[j]=aux;
i++;
j--;
}
}
if(left<j) //recursion
quicksort(v, left, j); // in the left side
if(i<right)
quicksort(v, i, right); // in the right side
}
|
The rest of the program is like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include<iostream>
using namespace std;
void quicksort(int v[100], int left, int right); //function prototype
int v[100], i, n;
int main()
{ cout<<"n=";
cin>>n;
for(i=1; i<=n; i++)
{ cout<<"v["<<i<<"]=";
cin>>v[i];
}
quicksort(v, 1, n);
for(i=1; i<=n; i++)
{ cout<<v[i]<<" ";
}
return 0;
}
|
And after that, you have to write the function quicsort which is below.
The mechanism is very simple: the algorithm "split" the vector in two parts (at the beginning) and then he sorts the numbers in those 2 parts. Then, with the recursion, the vector is "split" in more parts and the mechanism continues. I said "split" with quotes because the vector is not split (for real), the algorithm just works with a part of it.
Check this:
http://www.cs.oswego.edu/~mohammad/classes/csc241/samples/sort/Sort2-E.html. Is a plugin (a kind of game) wrote in Java. It helps you to understand more those algorithms. There are 3 or 4 algorithms (Buble-sort, Insert sort, quicksort and another one...I don't remember it right now). If you didin't understand something, tell me.