Skip to content

Commit a4420fc

Browse files
authored
Merge pull request #207 from Sreemoyee26/main
Added Selection Sort in C++
2 parents c376104 + 2753d3c commit a4420fc

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Sorting/SelectionSort.cpp

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// C++ program for selection sort
2+
#include <bits/stdc++.h>
3+
using namespace std;
4+
5+
void swap(int *xp, int *yp)
6+
{
7+
int temp = *xp;
8+
*xp = *yp;
9+
*yp = temp;
10+
}
11+
12+
void selectionSort(int arr[], int n)
13+
{
14+
int i, j, min_idx;
15+
16+
// One by one move boundary of unsorted subarray
17+
for (i = 0; i < n-1; i++)
18+
{
19+
// Find the minimum element in unsorted array
20+
min_idx = i;
21+
for (j = i+1; j < n; j++)
22+
if (arr[j] < arr[min_idx])
23+
min_idx = j;
24+
25+
// Swap the found minimum element with the first element
26+
swap(&arr[min_idx], &arr[i]);
27+
}
28+
}
29+
30+
// Function to print the array
31+
void printArray(int arr[], int size)
32+
{
33+
int i;
34+
for (i=0; i < size; i++)
35+
cout << arr[i] << " ";
36+
cout << endl;
37+
}
38+
39+
// Driver code
40+
int main()
41+
{
42+
int arr[] = {4, 25, 14, 23, 11, -7, 44, -13, 25};
43+
int n = sizeof(arr)/sizeof(arr[0]);
44+
selectionSort(arr, n);
45+
cout << "Sorted array: \n";
46+
printArray(arr, n);
47+
return 0;
48+
}
49+
50+
// This code is contributed by Sreemoyee Sadhukhan

0 commit comments

Comments
 (0)