Bubble Sort Program In C++ Using Array

4 min read Jul 01, 2024
Bubble Sort Program In C++ Using Array

Bubble Sort Program in C++ using Array

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.

Algorithm:

  1. Start at the beginning of the array.
  2. Compare the current element with the next element.
  3. If the current element is greater than the next element, swap them.
  4. Repeat steps 2 and 3 for the entire array.
  5. Repeat steps 1 to 4 until the array is sorted.

C++ Implementation:

#include 
using namespace std;

// Function to perform bubble sort
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]) {
        // Swap elements if they are in the wrong order
        int temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
    }
  }
}

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

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

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

  bubbleSort(arr, n);

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

  return 0;
}

Explanation:

  • bubbleSort(int arr[], int n): This function takes an array arr and its size n as input.
  • Outer Loop (for (int i = 0; i < n - 1; i++)): This loop iterates through the array n - 1 times.
  • Inner Loop (for (int j = 0; j < n - i - 1; j++)): This loop compares adjacent elements in the array.
  • Swap Elements: If the current element is greater than the next element, the if condition is true, and the elements are swapped using a temporary variable.

Output:

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

Time and Space Complexity:

  • Time Complexity: O(n^2), where n is the size of the array.
  • Space Complexity: O(1), as it only uses a constant amount of extra space.

Advantages:

  • Easy to understand and implement.
  • Relatively efficient for small arrays.

Disadvantages:

  • Not efficient for large arrays.
  • Not stable, meaning that the relative order of equal elements is not preserved.

Conclusion:

Bubble Sort is a simple sorting algorithm that is easy to understand and implement. However, it is not efficient for large arrays and has a time complexity of O(n^2). It is better suited for small arrays or for educational purposes.

Latest Posts