C++ Online Compiler
Example: Selection Sort using Function in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Selection Sort using Function #include <iostream> // For input/output operations #include <algorithm> // For std::swap // Function to swap two elements void swap(int* xp, int* yp) { int temp = *xp; *xp = *yp; *yp = 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; } // Function to perform Selection Sort on an array void selectionSort(int arr[], int n) { int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n - 1; i++) { // Find the minimum element in unsorted array min_idx = i; for (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 part // std::swap(arr[min_idx], arr[i]); // Can use std::swap from <algorithm> swap(&arr[min_idx], &arr[i]); // Using custom swap function } } int main() { // Step 1: Initialize an unsorted array int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr) / sizeof(arr[0]); std::cout << "Original array: "; printArray(arr, n); // Step 2: Call the selectionSort function to sort the array selectionSort(arr, n); std::cout << "Sorted array: "; // Step 3: Print the sorted array printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS