-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelection_sort.cpp
More file actions
40 lines (34 loc) · 844 Bytes
/
Copy pathSelection_sort.cpp
File metadata and controls
40 lines (34 loc) · 844 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
#include <bits/stdc++.h>
using namespace std;
// Time Complexity = O(n^2).
// Space Complexity = O(1).
void selectionSort(int a[], int n)
{
// outer loop will run (n-1) times
for (int i = 0; i < n - 1; i++)
{
int smallestIndex = i;
bool isSwapped = false; // useful if array is already sorted
for (int j = i + 1; j < n; j++)
{
if (a[j] < a[smallestIndex])
{
smallestIndex = j;
isSwapped = true;
}
}
if(isSwapped == false)
break;
swap(a[i], a[smallestIndex]);
}
// Printing the sorted array.
for (int i = 0; i < n; i++)
cout << a[i] << " ";
}
int main()
{
int a[] = {3, 4, 1, 2, 5};
int n = sizeof(a) / sizeof(a[0]);
selectionSort(a, n);
return 0;
}