-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathselectionSort.cpp
More file actions
45 lines (37 loc) · 828 Bytes
/
selectionSort.cpp
File metadata and controls
45 lines (37 loc) · 828 Bytes
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
// Selection sort in C++
#include<iostream>
using namespace std;
// function to swap two elements
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
// function to print array
void printArr(int arr[], int n) {
for(int i=0; i<n; i++) {
cout<<arr[i]<<" ";
}
cout<<endl;
}
// function for Selection Sort
int *selectionSort(int arr[], int n) {
for(int i=0; i<n; i++) {
for(int j=i+1; j<n-1; j++) {
if(arr[i] > arr[j]) {
swap(arr[i], arr[j]);
}
}
}
return arr;
}
int main() {
int unsortedArr[7] = {3, 7, 2, 8, 1, 0, 9};
int size = sizeof(unsortedArr)/sizeof(unsortedArr[0]);
cout<<"Unsorted Array : ";
printArr(unsortedArr, size);
int *sortedArr = selectionSort(unsortedArr, size);
cout<<"Sorted Array : ";
printArr(sortedArr, size);
return 0;
}