-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelection_Sort.cpp
More file actions
48 lines (42 loc) · 914 Bytes
/
Selection_Sort.cpp
File metadata and controls
48 lines (42 loc) · 914 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
47
48
#include <iostream>
using namespace std;
// Selection Sort Function
void selectionSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int min_index = i;
for (int j = i + 1; j < n; j++)
{
if (arr[j] < arr[min_index])
{
min_index = j;
}
}
if (min_index != i)
{
swap(arr[i], arr[min_index]);
}
}
}
int main()
{
int arr[] = {5, 2, 4, 1, 3};
int n = sizeof(arr) / sizeof(arr[0]);
// print unsorted array
cout << "Unsorted array: ";
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
selectionSort(arr, n);
// print sorted array
cout << "Sorted array: ";
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
return 0;
}