Skip to content

Commit 738f5a6

Browse files
authored
Create SelectionSort.cpp
1 parent eb24641 commit 738f5a6

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Algorithms/Sorting/SelectionSort.cpp

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

0 commit comments

Comments
 (0)