-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy path06 SelectionSort.cpp
More file actions
46 lines (38 loc) · 862 Bytes
/
06 SelectionSort.cpp
File metadata and controls
46 lines (38 loc) · 862 Bytes
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
#include <iostream>
using namespace std;
template <class T>
void Print(T& vec, int n, string s){
cout << s << ": [" << flush;
for (int i=0; i<n; i++){
cout << vec[i] << flush;
if (i < n-1){
cout << ", " << flush;
}
}
cout << "]" << endl;
}
void swap(int* x, int* y){
int temp = *x;
*x = *y;
*y = temp;
}
void SelectionSort(int A[], int n){
for (int i=0; i<n-1; i++){
int j;
int k;
for (j=k=i; j<n; j++){
if (A[j] < A[k]){
k = j;
}
}
swap(&A[i], &A[k]);
}
}
int main() {
int A[] = {3, 7, 9, 10, 6, 5, 12, 4, 11, 2};
int n = sizeof(A)/sizeof(A[0]);
Print(A, n, "\t\tA");
SelectionSort(A, n);
Print(A, n, " Sorted A");
return 0;
}