File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments