-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselectionSort.cpp
50 lines (39 loc) · 1.42 KB
/
selectionSort.cpp
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
#include <iostream>
using namespace std;
void swap(int * arrPtr, int index1, int index2) {
int temp = arrPtr[index1];
arrPtr[index1] = arrPtr[index2];
arrPtr[index2] = temp;
}
void swapSmallerValuesToFront(int arr [],
int outerIndex,
int lastIndex) {
for (int innerIndex = outerIndex + 1; innerIndex <= lastIndex; innerIndex++) {
// the value at outerIndex may always change because
// it may be switched with previous elements that are smaller
// than it. That's why we must access the outerIndex value
// every time here.
if (arr[innerIndex] < arr[outerIndex]) {
cout << " We need to swap because current element is smaller" << endl;
swap(arr, innerIndex, outerIndex);
}
}
}
void selectionSort(int arr [], int size) {
cout << "size: " << size << endl;
int lastIndex = size - 1;
for (int pass = 0; pass <= lastIndex - 1; pass++) {
cout << "----> Outer Index: " << pass << endl;
swapSmallerValuesToFront(arr, pass, lastIndex);
}
}
int main() {
int intArray [] = {13,61,44,88,1,34,54,12,22,2,4,6,3,5,7};
int arrSize = sizeof(intArray)/sizeof(int);
selectionSort(intArray, arrSize);
// display the results
for ( int i = 0; i < arrSize; i++) {
cout << intArray[i] << endl;
}
return 0;
}