C Online Compiler
Example: Selection Sort in Descending Order in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Selection Sort in Descending 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 in descending order void selectionSortDescending(int arr[], int n) { int i, j, max_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n - 1; i++) { // Find the maximum element in unsorted array max_idx = i; for (j = i + 1; j < n; j++) { if (arr[j] > arr[max_idx]) { max_idx = j; } } // Swap the found maximum element with the first element of the unsorted subarray swap(&arr[max_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: Initialize an array and its size 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: Call selection sort function to sort in descending order selectionSortDescending(arr, n); // Step 4: Print the sorted array printf("Sorted array (descending): "); printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS