In this tutorial, we will learn and write a C program to implement selection sort using function. Before that you may go through the following topics in C:
Selection Sort Algorithm
The selection sort is a simple sorting algorithm which is an in-place comparison-based algorithm. It has two parts where the left end has a sorted part and the right end has an unsorted part.
In the beginning, the left end is empty and the right end has all the elements then the smallest element from the right end is brought to the left end and swapped with the leftmost element. This process continues until the element from the right end is brought to the left by swapping.
Although, it may cause a problem with the large inputs.
Implementation of Selection sort in C
Question: Selection sort program in C using function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | // implementation of selection sort in C program #include <stdio.h> void selectionSort(int arr[], int n) { int i, j, min, temp; for (i = 0; i < n - 1; i++) { // finding the minimum min = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min]) min = j; // Swapping temp = arr[min]; arr[min] = arr[i]; arr[i] = temp; } } int main() { int arr[30], n, i; printf("Enter the number of elements: "); scanf("%d", &n); printf("Enter %d Elements:\n", n); for (i = 0; i < n; i++) { scanf("%d", &arr[i]); } //calling sorting function selectionSort(arr, n); //Display the result printf("\nArray after sorting: \n"); for (i = 0; i < n; i++) printf("%d ", arr[i]); return 0; } |
Output:
Enter the number of elements: 6
Enter 6 Elements:
25
12
88
5
76
50
Array after sorting:
5 12 25 50 76 88
Time Complexity of Selection Sort:
- Best case:
0(n^2)
- Average case:
0(n^2)
- Worst case:
0(n^2)