bubble sort in c+

Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. Here is an example of bubble sort implementation in C++:

#include <iostream>
using namespace std;

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    bubbleSort(arr, n);
    cout << "Sorted array: \n";
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    return 0;
}

Explanation for each step:

  1. The bubbleSort function takes two parameters: an array arr and its size n.

  2. The outer loop for (int i = 0; i < n - 1; i++) runs from the first element of the array to the second-to-last element. It represents the number of passes through the list.

  3. The inner loop for (int j = 0; j < n - i - 1; j++) runs from the first element to the last unsorted element of the array. It compares adjacent elements and swaps them if they are in the wrong order.

  4. Inside the inner loop, the if (arr[j] > arr[j + 1]) condition checks if the current element is greater than the next element. If it is, a swap is performed using a temporary variable temp.

  5. After the inner loop completes for each pass, the largest element of the unsorted part of the array "bubbles" up to its correct position.

  6. This process continues until the entire array is sorted.

  7. The main function initializes an array arr, calculates its size n, calls the bubbleSort function, and then prints the sorted array.

  8. The sorted array is printed using the cout statement inside the for loop.

  9. Finally, the main function returns 0, indicating successful execution of the program.