Exchange Sort


Exchange sort, also known as bubble sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items, and swaps them if they are in the wrong order. This process is repeated until the entire list is sorted.

Algorithm

ALGORITHM BubbleSort(A[0..n − 1])
// Sorts a given array by bubble sort
// Input: An array A[0..n − 1] of orderable elements
// Output: Array A[0..n − 1] sorted in nondecreasing order

for i ← 0 to n − 2 do
    for j ← 0 to n − 2 − i do
        if A[j + 1] < A[j]
            swap A[j] and A[j + 1]

Write a C++ program to implement exchange/bubble sort

#include <iostream>

void bubbleSort(int A[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - 1 - i; j++) {
            if (A[j + 1] < A[j]) {
                // Swap A[j] and A[j + 1]
                int temp = A[j];
                A[j] = A[j + 1];
                A[j + 1] = temp;
            }
        }
    }
}

// Function to print the array
void printArray(int A[], int n) {
    for (int i = 0; i < n; i++) {
        std::cout << A[i] << " ";
    }
    std::cout << std::endl;
}

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

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

    bubbleSort(A, n);

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

    return 0;
}

Output

Original array: 64 25 12 22 11 
Sorted array: 11 12 22 25 64 

Sort the given list of numbers using bubble sort: 45,2,20,6,3