📊📚Intermediate
Sort Array Using Selection Sort
Sort using selection sort
Selection Sort finds the minimum element and places it at the beginning. Repeats for the remaining unsorted portion.
Program Code
selection_sort.c
C
1#include <stdio.h>23int main() {4 int n;5 6 printf("Enter number of elements: ");7 scanf("%d", &n);8 9 int arr[n];10 printf("Enter %d elements: ", n);11 for (int i = 0; i < n; i++) {12 scanf("%d", &arr[i]);13 }14 15 // Selection Sort16 for (int i = 0; i < n - 1; i++) {17 int minIdx = i;18 for (int j = i + 1; j < n; j++) {19 if (arr[j] < arr[minIdx]) {20 minIdx = j;21 }22 }23 // Swap minimum with first unsorted24 int temp = arr[i];25 arr[i] = arr[minIdx];26 arr[minIdx] = temp;27 }28 29 printf("Sorted array: ");30 for (int i = 0; i < n; i++) {31 printf("%d ", arr[i]);32 }33 printf("\n");34 35 return 0;36}Output
Enter number of elements: 5
Enter 5 elements: 64 25 12 22 11
Sorted array: 11 12 22 25 64
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials