📘 Lesson  ·  Lesson 77

Bubble Sort

Bubble Sort

💡 Note

Bubble sort repeatedly swaps adjacent out-of-order elements until the array is sorted.

Program

C++
#include <iostream>
using namespace std;
int main() {
    int a[] = {5, 2, 8, 1, 9}, n = 5;
    for (int i = 0; i < n-1; i++)
        for (int j = 0; j < n-i-1; j++)
            if (a[j] > a[j+1]) swap(a[j], a[j+1]);
    for (int x : a) cout << x << " ";   // 1 2 5 8 9
    return 0;
}
Output:
1 2 5 8 9

Summary

  • Compare neighbours and swap; largest "bubbles" to the end each pass.
  • Time complexity O(n^2).

Bubble Sort

💡 Note

Bubble sort repeatedly swaps adjacent out-of-order elements until the array is sorted.

Program

C++
#include <iostream>
using namespace std;
int main() {
    int a[] = {5, 2, 8, 1, 9}, n = 5;
    for (int i = 0; i < n-1; i++)
        for (int j = 0; j < n-i-1; j++)
            if (a[j] > a[j+1]) swap(a[j], a[j+1]);
    for (int x : a) cout << x << " ";   // 1 2 5 8 9
    return 0;
}
Output:
1 2 5 8 9

सारांश

  • Compare neighbours and swap; largest "bubbles" to the end each pass.
  • Time complexity O(n^2).
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 लाइव कोड एडिटर

इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.