Selection Sort in Ascending Order in C++

1. Introduction

In this blog post, we will learn how to write a C++ program to sort an array of integers in an Ascending Order using the Selection Sort algorithm.

Selection Sort is another fundamental sorting technique primarily taught to beginners in computer science. Its operation hinges on the premise of successively searching for the smallest (or largest, based on sorting order) element from the unsorted segment of the list and swapping it with the beginning element.

2. Program Overview

The C++ program will have the following structure:

1. swap(): A function to interchange two elements.

2. selectionSort(): The main function that sorts the array using Selection Sort.

3. printArray(): A function that renders the array contents.

4. main(): The primary function initiating the program.

3. Code Program

#include<iostream>
using namespace std;

// Utility function to swap two elements
void swap(int &x, int &y) {
    int temp = x;
    x = y;
    y = temp;
}

// Main function to perform selection sort
void selectionSort(int arr[], int n) {
    for (int i = 0; i < n-1; i++) {
        int min_idx = i; // Find the minimum element in unsorted array
        for (int j = i+1; j < n; j++) {
            if (arr[j] < arr[min_idx]) {
                min_idx = j;
            }
        }
        // Swap the found minimum element with the first element
        swap(arr[min_idx], arr[i]);
    }
}

// Function to print an array
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

// Driver function
int main() {
    int arr[] = {64, 25, 12, 22, 11};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << "Original array: \n";
    printArray(arr, n);

    selectionSort(arr, n);

    cout << "Sorted array in ascending order: \n";
    printArray(arr, n);
    return 0;
}

Output:

Original array:
64 25 12 22 11 
Sorted array in ascending order: 
11 12 22 25 64 

4. Step By Step Explanation

1. swap(): A simple utility that swaps two elements. It's frequently used in our selection sort function when the current minimum is identified.

2. selectionSort(): This is the heart of the program. For every pass, the function searches for the smallest element from the unsorted segment and swaps it with the starting element.

3. printArray(): A straightforward function displaying the array elements, offering a visual contrast before and after the sorting.

4. main(): The driver function. It instantiates an example array, showcases its contents, applies the selection sort, and then presents the sorted array.

The Selection Sort algorithm is distinct for its simplicity, but it's not particularly fast for extensive datasets. With both worst-case and average-case time complexity of O(n^2), it's advised to leverage more efficient algorithms like QuickSort or MergeSort for large-scale sorting tasks.

Related C++ Programs on Sorting Algorithms

Comments