Bubble Sort Algorithm in CPP

1. Introduction

Selection Sort is a straightforward sorting algorithm that works by repeatedly selecting the smallest (or largest, depending on the sorting order) element from the unsorted sub-array and swapping it with the first unsorted element. This process moves the smallest (or largest) element to its correct position.

2. Implementation Steps

1. Start with the first element as the minimum.

2. Search the minimum element from the array.

3. Swap it with the value at the first location.

4. Select the next element as minimum and repeat the process until all elements are sorted.

3. Implementation in C++ Programming

void selectionSort(int arr[], int n) {
    for (int i = 0; i < n-1; i++) {
        int min_idx = i; // Assume current index as minimum
        for (int j = i+1; j < n; j++) {
            // If a smaller number is found, update the minimum index
            if (arr[j] < arr[min_idx]) {
                min_idx = j;
        // Swap the smallest number found with the first number
        int temp = arr[min_idx];
        arr[min_idx] = arr[i];
        arr[i] = temp;
int main() {
    int arr[] = {64, 25, 12, 22, 11};
    int n = sizeof(arr) / sizeof(arr[0]);
    selectionSort(arr, n);
    std::cout << "Sorted array: \n";
    for (int i = 0; i < n; i++) {
        std::cout << arr[i] << " ";
    std::cout << std::endl;
    return 0;


Sorted array:
11 12 22 25 64


1. The selectionSort function takes an array and its length as arguments.

2. It begins by assuming the first element of the array to be the smallest.

3. As we move through the array, if a smaller number is found, we update the index of the smallest number.

4. Once the entire array has been traversed, we swap the smallest number found with the first element of the array.

5. The process is repeated with the remaining part of the array until the entire array is sorted.

6. In the main function, we have defined an unsorted array. After sorting using the selectionSort function, the sorted array is printed to the console.