C Online Compiler
Example: Selection Sort Algorithm in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Selection Sort Algorithm #include <stdio.h> // Function to swap two elements void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } // Function to print an array void printArray(int arr[], int size) { int i; for (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; // Step 1: Traverse through all array elements for (i = 0; i < n - 1; i++) { // Step 2: 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; } } // Step 3: Swap the found minimum element with the first element // of the unsorted part (at index 'i') swap(&arr[min_idx], &arr[i]); printf("Array after pass %d: ", i + 1); printArray(arr, n); } } int main() { // Step 1: Initialize an unsorted array int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr) / sizeof(arr[0]); printf("Original array: "); printArray(arr, n); // Step 2: Apply selection sort selectionSort(arr, n); // Step 3: Print the sorted array printf("\nSorted array: "); printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS