Skip to content

Commit c964591

Browse files
authored
Create Sel_Sort.cpp
1 parent b1977a2 commit c964591

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Sel_Sort.cpp

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// C++ program for implementation of 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 an 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 program to test above functions
40+
int main()
41+
{
42+
int arr[] = {64, 25, 12, 22, 11};
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 is code is contributed by rathbhupendra

0 commit comments

Comments
 (0)