summaryrefslogtreecommitdiff
path: root/algorithms/quick_sort.cc
blob: 88d9e01680dd84f5af0c79d20eba480e1a3c0fa3 (plain)
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
50
51
52
53
54
55
56
57
58
#include <iostream>

#define N 4

using namespace std;


void
quickSort(int *A, int l, int r)
{
  int i,j,v,t;
  /* trivial case */
  if (r <= l) return;
  /* chose pivot */
  v = A[r];
  i = l-1;
  j = r;
  /* identify parts */
  do {
    /* left.. */
    do {i++;} while(A[i]<v);
    /* right.. */
      do {j--;} while (A[j]>v);
        if (i<j) {
          /* swap */
          t = A[i];
          A[i] = A[j];
          A[j] = t;
        }
        else {
          /* pivot at [i] */
          t = A[i];
          A[i] = A[r];
          A[r] = t;
        }
    } while (i<j);
    /* sort parts */
    quickSort(A,l,i-1);
    quickSort(A,i+1,r);
}

int
main (int argc, char * const argv[]) {
  int A[N] = {3,1,1,2};

  for(unsigned int i=0; i<N; i++) {
    cout << A[i];
  }
  cout << endl << "sortiert:" << endl;
  quickSort(A, 0, N);
  for(unsigned int i=0; i<N; i++) {
    cout << A[i];
  }
  cout << endl;

  return 0;
}