C Online Compiler
Example: Selection Sort in Ascending Order in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Selection Sort in Ascending Order #include <stdio.h> // Function to swap two elements void swap(int* xp, int* yp) { int temp = *xp; *xp = *yp; *yp = temp; } // Function to perform selection sort on an array 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]); } } // 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"); } int main() { // Step 1: Define an array to be sorted int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr) / sizeof(arr[0]); // Step 2: Print the original array printf("Original array: \n"); printArray(arr, n); // Step 3: Call the selection sort function selectionSort(arr, n); // Step 4: Print the sorted array printf("Sorted array: \n"); printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS