Skip to content

Commit 2ceac8c

Browse files
authored
Add files via upload
1 parent 118f6d4 commit 2ceac8c

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Selection Sort/main (2).c

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// selection sort
2+
3+
#include <stdio.h>
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+
if(min_idx != i)
27+
swap(&arr[min_idx], &arr[i]);
28+
}
29+
}
30+
31+
/* Function to print an array */
32+
void printArray(int arr[], int size)
33+
{
34+
int i;
35+
for (i=0; i < size; i++)
36+
printf("%d ", arr[i]);
37+
printf("\n");
38+
}
39+
40+
// Driver program to test above functions
41+
int main()
42+
{
43+
int arr[] = {64, 25, 12, 22, 11};
44+
int n = sizeof(arr)/sizeof(arr[0]);
45+
selectionSort(arr, n);
46+
printf("Sorted array: \n");
47+
printArray(arr, n);
48+
return 0;
49+
}

0 commit comments

Comments
 (0)