Pages

Friday, April 11, 2025

Bubble Sort in C++

#include <iostream>
#include <vector>
#include <algorithm> // for sort
using namespace std;


void print(int arr[], int n) {
    for(int i=0; i<n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

void bubbleSort(int arr[], int n) {

    //outer loop
    for(int i=0; i<n-1; i++) {

        //inner loop
        for(int j=0;  j<n-i-1; j++) {
            if(arr[j] > arr[j+1]) {  // < -> descending order , > -> ascending order
                swap(arr[j], arr[j+1]);
            }
        }
    }

    print(arr, n);
}

int main() {
    // int arr[5] = {5, 4, 1, 3, 2};
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    bubbleSort(arr, 10);


    return 0;
}


OUTPUT-
1 2 3 4 5 6 7 8 9 10

No comments:

Post a Comment

Encode and Decode Strings - NeetCode.IO Solution by me + gemini pro 3.0 explained

  class Solution {         // encode: List of Strings -> String     public String encode ( List < String > strs) {         Stri...