-
Notifications
You must be signed in to change notification settings - Fork 208
/
Copy pathSelectionSort.cpp
39 lines (38 loc) · 902 Bytes
/
SelectionSort.cpp
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;
void swapping(int &p, int &q) {
int temp;
temp = p;
p = q;
q = temp;
}
void display(int *a, int size) { //to display array elements
for(int i = 0; i<size; i++)
cout << a[i] << " ";
cout << "\n";
}
void selectionSort(int *a, int size) {
int i, j, min;
for(i = 0; i<size-1; i++) {
min = i;
for(j = i+1; j<size; j++)
if(a[j] < a[min])
min = j;
swapping(a[i], a[min]);
}
}
int main() {
int n; //size of array
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter elements:" << "\n";
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array Elements before Sorting: ";
display(arr, n);
selectionSort(arr, n);
cout << "Array Elements after Sorting: ";
display(arr, n);
}