Scroll Progress Bar

Selection sort

Selection sort is a simple sorting algorithm that works by repeatedly selecting the minimum element from an unsorted portion of an array and placing it at the beginning. Here's how it can implement selection sort in C++:

Program:

#include <iostream>

void selectionSort(int arr[], int size) {
    for (int i = 0; i < size - 1; i++) {
        int minIndex = i;

        // Find the index of the minimum element in the unsorted portion
        for (int j = i + 1; j < size; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }

        // Swap the minimum element with the first element of the unsorted portion
        if (minIndex != i) {
            std::swap(arr[i], arr[minIndex]);
        }
    }
}

int main() {
    int arr[] = {64, 25, 12, 22, 11};
    int size = sizeof(arr) / sizeof(arr[0]);

    std::cout << "Original array: ";
    for (int i = 0; i < size; i++) {
        std::cout << arr[i] << " ";
    }

    selectionSort(arr, size);

    std::cout << "\nSorted array: ";
    for (int i = 0; i < size; i++) {
        std::cout << arr[i] << " ";
    }

    return 0;
}
In this code:
  • selectionSort is a function that takes an array arr and its size size as parameters and sorts the array in ascending order using the selection sort algorithm.
  • The outer loop (with index i) iterates through the array from the beginning to the second-to-last element.
  • In each iteration of the outer loop, the inner loop (with index j) searches for the minimum element in the unsorted portion of the array (from index i+1 to the end).
  • If a smaller element is found, its index is stored in minIndex.
  • After finding the minimum element in the unsorted portion, a swap is performed to move the minimum element to its correct position in the sorted portion.
  • The selection sort algorithm continues until the entire array is sorted.
  • When run this code, it will sort the arr array in ascending order using selection sort and print both the original and sorted arrays.

question


answer

question2


answer2