C++ Online Compiler
Example: Selection Sort in Ascending Order in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Selection Sort in Ascending Order #include <iostream> #include <vector> // Using vector for dynamic array, can also use fixed-size array #include <algorithm> // For std::swap void selectionSort(std::vector<int>& arr) { int n = arr.size(); // Step 1: Iterate through the array 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 // This places the smallest element at its correct sorted position if (min_idx != i) { // Only swap if min_idx is not already the current position std::swap(arr[i], arr[min_idx]); } } } void printArray(const std::vector<int>& arr) { for (int i = 0; i < arr.size(); ++i) { std::cout << arr[i] << " "; } std::cout << std::endl; } int main() { // Step 1: Define an unsorted array std::vector<int> arr = {64, 25, 12, 22, 11}; std::cout << "Original array: "; printArray(arr); // Step 2: Apply selection sort selectionSort(arr); // Step 3: Print the sorted array std::cout << "Sorted array (ascending): "; printArray(arr); // Additional test case std::vector<int> arr2 = {5, 1, 4, 2, 8}; std::cout << "Original array 2: "; printArray(arr2); selectionSort(arr2); std::cout << "Sorted array 2 (ascending): "; printArray(arr2); return 0; }
Output
Clear
ADVERTISEMENTS