-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSelectionSort.cpp
More file actions
57 lines (42 loc) · 1.2 KB
/
SelectionSort.cpp
File metadata and controls
57 lines (42 loc) · 1.2 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
#include <iostream>
using namespace std;
// SELECTION SORT
// The inner loop selects the minimum element in the unsorted array and places the elements in increasing order.
// Time complexity = O(n^2)
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << "\n";
}
int main() {
const int MAX_SIZE = 100;
int size;
int arr[MAX_SIZE];
cout << "Enter the size of array: ";
cin>>size;
if (size > MAX_SIZE) {
cout << "Size exceeds maximum allowed size of " << MAX_SIZE << endl;
return 1;
}
cout << "Enter the elements of the array:";
for (int i = 0; i < size; i++) {
cin >> arr[i];
}
cout << "Array before sorting:";
printArray(arr, size);
// Sorting Mechanism
for(int i = 0; i < size; i++) {
int smallest = i;
for(int j = i+1; j < size; j++) {
if(arr[smallest] > arr[j]) {
smallest = j;
}
}
int temp = arr[smallest];
arr[smallest] = arr[i];
arr[i] = temp;
}
cout << "Array after sorting:";
printArray(arr, size);
}