C++ Online Compiler
Example: Selection Sort Ascending in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Selection Sort Ascending #include <iostream> // Required for input/output operations #include <algorithm> // Required for std::swap (or you can implement manually) void selectionSort(int arr[], int n) { // Step 1: Traverse through all array elements for (int i = 0; i < n - 1; i++) { // Step 2: Find the minimum element in the unsorted part of the array int min_idx = i; for (int 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 // std::swap(arr[min_idx], arr[i]); // Using standard library swap // Manual swap implementation: int temp = arr[min_idx]; arr[min_idx] = arr[i]; arr[i] = temp; } } // Function to print an array void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { std::cout << arr[i] << " "; } std::cout << std::endl; } int main() { int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr) / sizeof(arr[0]); std::cout << "Original array: "; printArray(arr, n); selectionSort(arr, n); std::cout << "Sorted array: "; printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS