selection sort c++ algorithm

Selection Sort Algorithm in C++

The selection sort algorithm is a simple comparison-based sorting algorithm. It works by dividing the input array into two parts: the sorted part and the unsorted part. In each iteration, it selects the smallest (or largest) element from the unsorted part and moves it to the sorted part.

Here is the step-by-step explanation of the selection sort algorithm in C++:

  1. Start with an unsorted array arr of size n.

  2. Iterate through the array from the first element i = 0 to i = n-1.

  3. Set minIndex as the index of the minimum element in the unsorted part (i to n-1).

  4. Iterate through the unsorted part of the array from j = i+1 to j = n-1.

  5. If arr[j] is less than arr[minIndex], update minIndex to j.

  6. After the inner loop, swap the minimum element (arr[minIndex]) with the current element (arr[i]).

  7. Repeat steps 2 to 6 until the array is completely sorted.

  8. The array is now sorted in ascending order.

C++ Code Example:

#include <iostream>

void selectionSort(int arr[], int n) {
    for (int i = 0; i < n-1; i++) {
        int minIndex = i;
        for (int j = i+1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        std::swap(arr[i], arr[minIndex]);
    }
}

int main() {
    int arr[] = {64, 25, 12, 22, 11};
    int n = sizeof(arr)/sizeof(arr[0]);
    selectionSort(arr, n);
    std::cout << "Sorted array: ";
    for (int i = 0; i < n; i++) {
        std::cout << arr[i] << " ";
    }
    return 0;
}

This code snippet demonstrates the implementation of the selection sort algorithm in C++. The selectionSort function takes an array arr and its size n as parameters. It performs the selection sort algorithm and sorts the array in ascending order. The main function initializes an array, calls the selectionSort function, and prints the sorted array.