?? Understanding Bubble Sort: A Simple Sorting Algorithm

?? Understanding Bubble Sort: A Simple Sorting Algorithm

Bubble Sort , a fundamental sorting algorithm, operates by stepping through a list, comparing adjacent elements, and swapping them if they're in the incorrect order. This uncomplicated process continues until the entire list is correctly arranged.

How Bubble Sort Works:

Algorithm Overview:

1. Comparing Adjacent Elements:

- Bubble sort examines each pair of neighboring items in the list.

2. Swapping Elements:

- If elements are out of order, they get swapped (e.g., if a smaller element appears after a larger one in ascending order).

3. Repeating Until Sorted:

- The algorithm repeats these steps for multiple passes until no more swaps are necessary.

4. Optimization:

- After each pass, the largest (or smallest) element reaches its correct position at the end of the array.

Bubble Sort in Action:

Initial Array: [5, 4, 3, 2, 1]

Step-by-Step Progress:

  • Pass 1: [4, 3, 2, 1, 5]
  • Pass 2: [3, 2, 1, 4, 5]
  • Pass 3: [2, 1, 3, 4, 5]
  • Pass 4: [1, 2, 3, 4, 5]

Through iterative comparisons and swaps, Bubble Sort arranges the array in ascending order.

A simple implementation of the Bubble Sort algorithm in C++ :

#include <iostream>
using namespace std;
int main(){
    int n;
    cout << "Enter the size of array : ";
    cin >> n;
    int* arr = new int[n];
    cout << "Enter "<<n<< " elements for the array : ";
    for(int i = 0; i < n; i++){
        cin >> arr[i];
    }
 
    for(int i = n-2; i >= 0; i--){
        bool swapped = 0;
        for(int j = 0; j <= i; j++){
            if(arr[j] > arr[j+1]){
                swap(arr[j], arr[j+1]);
                swapped = 1;
            }
            if(swapped == 0)
            break;
        }
    }
    cout << "Sorted array by Bubble Sort : ";
    for(int i = 0; i < n; i++){
        cout << arr[i]<<" ";
    }
    delete[] arr;
    return 0;
}        

Complexity Analysis:

- Time Complexity: O(n^2) - Involves nested loops for comparison and swapping.

- Space Complexity: O(1) - Sorts the array in-place without additional space.


Bubble sort's simplicity makes it ideal for educational purposes or small datasets. However, its quadratic time complexity makes it less efficient for larger datasets.

要查看或添加评论,请登录

Prince Kumar的更多文章

社区洞察

其他会员也浏览了