C Online Compiler
Example: Selection Sort in C (Ascending Order) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Selection Sort in C (Ascending Order) #include <stdio.h> // Function to swap two integers void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } // Function to print an array void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } // Function to perform selection sort void selectionSort(int arr[], int n) { int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n - 1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i + 1; j < n; j++) { if (arr[j] < arr[min_idx]) { min_idx = j; } } // Swap the found minimum element with the first element // of the unsorted subarray (at index 'i') swap(&arr[min_idx], &arr[i]); } } int main() { // Step 1: Initialize an array int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr) / sizeof(arr[0]); // Step 2: Print the original array printf("Original array: "); printArray(arr, n); // Step 3: Perform selection sort selectionSort(arr, n); // Step 4: Print the sorted array printf("Sorted array: "); printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS