C++ Online Compiler
Example: Selection Sort in C++ in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Selection Sort in C++ #include <iostream> #include <algorithm> // Required for std::swap // 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; } // Function to perform Selection Sort void selectionSort(int arr[], int n) { // One by one move boundary of unsorted subarray for (int i = 0; i < n - 1; i++) { // Find the minimum element in 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 std::swap(arr[min_idx], arr[i]); } } int main() { // Step 1: Initialize an unsorted array int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr) / sizeof(arr[0]); // Step 2: Print the original array std::cout << "Original array: "; printArray(arr, n); // Step 3: Apply Selection Sort selectionSort(arr, n); // Step 4: Print the sorted array std::cout << "Sorted array: "; printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS