-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathselection_sort.cpp
More file actions
39 lines (30 loc) · 778 Bytes
/
selection_sort.cpp
File metadata and controls
39 lines (30 loc) · 778 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
#include <iostream>
using namespace std;
// Function to perform Selection Sort
void selectionSort(int arr[], int n) {
for(int i = 0; i < n - 1; i++) {
int minIndex = i;
// Find minimum element
for(int j = i + 1; j < n; j++) {
if(arr[j] < arr[minIndex])
minIndex = j;
}
// Swap with first unsorted element
swap(arr[i], arr[minIndex]);
}
}
int main() {
int n;
cout << "Enter number of elements: ";
cin >> n;
int* arr = new int[n];
cout << "Enter elements:\n";
for(int i = 0; i < n; i++)
cin >> arr[i];
selectionSort(arr, n);
cout << "Sorted array: ";
for(int i = 0; i < n; i++)
cout << arr[i] << " ";
delete[] arr;
return 0;
}