Skip to content

Commit 6657bde

Browse files
Create selection_sort.cpp
1 parent d2889a2 commit 6657bde

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

selection_sort.cpp

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#include<iostream>
2+
using namespace std;
3+
void swapping(int &a, int &b) { //swap the content of a and b
4+
int temp;
5+
temp = a;
6+
a = b;
7+
b = temp;
8+
}
9+
void display(int *array, int size) {
10+
for(int i = 0; i<size; i++)
11+
cout << array[i] << " ";
12+
cout << endl;
13+
}
14+
void selectionSort(int *array, int size) {
15+
int i, j, imin;
16+
for(i = 0; i<size-1; i++) {
17+
imin = i; //get index of minimum data
18+
for(j = i+1; j<size; j++)
19+
if(array[j] < array[imin])
20+
imin = j;
21+
//placing in correct position
22+
swap(array[i], array[imin]);
23+
}
24+
}
25+
int main() {
26+
int n;
27+
cout << "Enter the number of elements: ";
28+
cin >> n;
29+
int arr[n]; //create an array with given number of elements
30+
cout << "Enter elements:" << endl;
31+
for(int i = 0; i<n; i++) {
32+
cin >> arr[i];
33+
}
34+
cout << "Array before Sorting: ";
35+
display(arr, n);
36+
selectionSort(arr, n);
37+
cout << "Array after Sorting: ";
38+
display(arr, n);
39+
}

0 commit comments

Comments
 (0)