summaryrefslogtreecommitdiff
path: root/algorithms/selection_sort.cc
blob: 1c42a78f8f64aeb1761358daae2261965e7785fc (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
#include <iostream>

#define N 4

using namespace std;


void
selectionSort(int *A, int n)
{
  int i, j, max, maxpos;
  for (j=n-1; j>0; j--) {
    /* find max between A[0],....A[j] */
    max = A[j];
    maxpos = j;
    for (i=j-1; i>=0; i--) {
      if (A[i]>max) {
        max = A[i];
        maxpos = i;
      }
    }
    /* swap */
    A[maxpos] = A[j];
    A[j] = max;
  }
}


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 << "sorted:" << endl;
  selectionSort(A, N);
  for(unsigned int i=0; i<N; i++) {
    cout << A[i];
  }
  cout << endl;

  return 0;
}