Quicksort question

I was hoping someone could explain how the quick() function and the partition() function works. I found this source code online. I have used pieces of it in my own code but I do not understand what it does, just that it does what I ask.

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
#include <iostream>
using namespace std;
void exch(int a[],int i,int j){
    int s=a[i];
    a[i]=a[j];
    a[j]=s;

}
int  partition(int a[],int l,int h);
void quick(int a[],int l,int h){
    if (h<=l) return ;
    int j=partition(a,l,h);
    quick(a,l,j-1);
    quick(a,j+1,h);
    }
int partition(int a[],int l,int h){
    int i=l-1;
    int j=h;
    int v=a[h];
    while(true){

        while( a[++i]<v);

        while(a[--j]>v) if (j==i)  break;

            if (i>=j) break;

        exch(a,i,j);

    }

    exch(a,i,h);
    return i;



}
int main(){

    int a[]={12,43,13,5,8,10,11,9,20,17};
    int n=sizeof(a)/sizeof(int);
quick(a,0,n-1);
 for (int  i=0;i<n;i++){
     cout<<a[i]<<"  ";
 }
     return 0;
 }

It outputs 


Also, line 41 confused me as well. Thanks in advance
Last edited on
Check out this link. It has code, too. And with better variable names.
http://www.algolist.net/Algorithms/Sorting/Quicksort

EDIT: line 41 gets the number of elements in the array a and stores that number in n.
Last edited on
Thanks for the link Booradley60, that was EXTREMELY helpful!

@Duoas, although I highly respect your replies, Your link was not as helpful as booradley60's link. I appreciate the assistance though!
Excellent feedback! Thank you!
@Duoas
When do those links (I saw some of the others in the lounge thread) "go live", at least in the sense of being able to browse to them from the homepage? I'd like to be able to find them and link them in these sort of questions to keep the page hits here.
Last edited on
Alas, I still have quite a bit to do... so it may be a while longer.
See http://www.cplusplus.com/forum/lounge/60389/ for a partial list. (My current list is a little more up to date, but still, my time is very frustratingly limited ATM...)
Topic archived. No new replies allowed.