C Online Compiler
Example: Selection Sort without Function in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Selection Sort without Function #include <stdio.h> int main() { // Step 1: Declare and initialize the array int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr) / sizeof(arr[0]); // Calculate the number of elements // Step 2: Print the original array printf("Original array: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); // Step 3: Implement Selection Sort logic // One by one, move the boundary of the unsorted subarray for (int i = 0; i < n - 1; i++) { // Find the minimum element in the unsorted array int min_idx = i; for (int 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 // This is done without a separate swap function int temp = arr[min_idx]; arr[min_idx] = arr[i]; arr[i] = temp; } // Step 4: Print the sorted array printf("Sorted array: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); return 0; }
Output
Clear
ADVERTISEMENTS