Skip to content

Commit 91826a7

Browse files
Merge pull request #91 from keshav-space/master
Added shorting algorithm in c++ language
2 parents 31823c7 + 26c38fa commit 91826a7

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

c-cpp/11_sorts/sorts.cpp

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

0 commit comments

Comments
 (0)