diff options
Diffstat (limited to 'algorithms/selection_sort.cc')
-rw-r--r-- | algorithms/selection_sort.cc | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/algorithms/selection_sort.cc b/algorithms/selection_sort.cc new file mode 100644 index 0000000..1c42a78 --- /dev/null +++ b/algorithms/selection_sort.cc @@ -0,0 +1,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; +} + |