Selection Sort Algorithm in C++

 

Program Explanation

The Selection Sort algorithm is a simple comparison-based sorting algorithm. It divides the input list into two parts: a sorted part and an unsorted part. The algorithm repeatedly selects the smallest (or largest, depending on sorting order) element from the unsorted part and moves it to the end of the sorted part.

Program Structure

  • Function selectionSort: This function takes an array and its size as parameters and sorts the array in ascending order using the Selection Sort algorithm.
  • Function printArray: This function prints the elements of the array to the console.
  • Function main: The entry point of the program. It initializes an array, calls the sorting function, and prints the sorted array.

C++ Code


#include <iostream>

using namespace std;

/**
 * Function to perform selection sort on an array.
 * @param arr The array to be sorted.
 * @param n The number of elements in the array.
 */
void selectionSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        // Find the index of the minimum element in the unsorted portion
        int minIndex = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        // Swap the found minimum element with the first element
        if (minIndex != i) {
            swap(arr[i], arr[minIndex]);
        }
    }
}

/**
 * Function to print the elements of an array.
 * @param arr The array to be printed.
 * @param n The number of elements in the array.
 */
void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

/**
 * The main function where the program execution begins.
 */
int main() {
    int arr[] = {64, 25, 12, 22, 11};
    int n = sizeof(arr) / sizeof(arr[0]);

    cout << "Original array: ";
    printArray(arr, n);

    selectionSort(arr, n);

    cout << "Sorted array: ";
    printArray(arr, n);

    return 0;
}
        

How to Compile and Run

  1. Copy the code into a file named selection_sort.cpp.
  2. Open a terminal and navigate to the directory containing the file.
  3. Compile the program using the command: g++ selection_sort.cpp -o selection_sort.
  4. Run the program with the command: ./selection_sort.

 

Explanation of the Code:

  1. Function selectionSort: This function iterates over the array, finds the minimum element from the unsorted portion, and swaps it with the first element of the unsorted portion.
  2. Function printArray: This function is used to display the elements of the array on the console.
  3. Function main: It initializes an example array, prints the original array, calls the selectionSort function to sort it, and then prints the sorted array.

Leave a Reply

Your email address will not be published. Required fields are marked *