-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselection_sort.cpp
More file actions
63 lines (49 loc) · 1.12 KB
/
selection_sort.cpp
File metadata and controls
63 lines (49 loc) · 1.12 KB
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
59
60
61
62
63
#include <iostream>
#include <stdlib.h>
#include <time.h>
//Use const instead of macros
const int NumElements = 10;
const int dataLimit = 30;
// Note the inline keyword and pass by reference
inline static void
swap (int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
// Note the array being passed by reference
static void
SelectionSort (int (&a)[NumElements])
{
for (int i = 0; i < NumElements; i++) {
int minIndex = i, min = a[i];
for (int j=i; j < NumElements; j++) {
if (a[j] < min) {
min = a[j];
minIndex = j;
}
}
swap (a[i], a[minIndex]);
}
}
int main ()
{
int a[NumElements];
// Initialize random seed
srand(time(NULL));
for (int i = 0; i < NumElements; i++) {
a[i] = rand () % dataLimit;
}
// std is the namespace. :: is the scope resolution operator
std::cout << "Input data" << std::endl;
for (int i = 0; i < NumElements; i++)
std::cout << a[i] << " ";
std::cout << std::endl;
SelectionSort (a);
std::cout << "Output data" << std::endl;
for (int i = 0; i < NumElements; i++)
std::cout << a[i] << " ";
std::cout << std::endl;
}