Skip to content

Commit 6e63d1f

Browse files
author
dipanmandal
authored
uploaded the selection sort algorithm
1 parent 104fcd8 commit 6e63d1f

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

selectionSort.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
void printArray(int* arr, int size){
5+
for(int i = 0 ; i < size; i++) cout<<arr[i]<<" ";
6+
cout<<endl;
7+
}
8+
9+
void selectionSort(int* arr, int n){
10+
for (int i = 0; i < n-1; i++){
11+
int min = i;//we take the first element in each iteration to be the minimum element
12+
for (int j = i + 1; j < n; j++){
13+
if (arr[j] < arr[min]) min = j;
14+
}
15+
16+
if(min != i) swap(arr[i], arr[min]); //if we find any index where the element is lower than the
17+
//minimum element we swap the values
18+
}
19+
}
20+
21+
int main(){
22+
int n;
23+
cout<<"enter the number of elements in the array: "<<endl;
24+
cin>>n;
25+
26+
int arr[n];
27+
28+
cout<<"enter the elements: "<<endl;
29+
30+
for(int i = 0; i < n; i++)cin>>arr[i];
31+
32+
cout<<"the unsorted array is: "<<endl;
33+
printArray(arr,n);
34+
35+
selectionSort(arr, n); //basically we find the minimum element in each iteration in the array
36+
37+
cout<<"the sorted array is: "<<endl;
38+
printArray(arr, n);
39+
}
40+

0 commit comments

Comments
 (0)