Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions CPP_Programs/Bubble_sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#include<bits/stdc++.h> // Includes all standard C++ libraries
using namespace std;

/*
Function: bubble_sort
Purpose : Sorts the array using Bubble Sort algorithm
Params : arr[] -> array to be sorted
n -> number of elements
*/
void bubble_sort(int arr[], int n){

// Outer loop controls number of passes
// After each pass, the largest element moves to the end
for(int i = n - 1; i >= 0; i--){

// Inner loop compares adjacent elements
for(int j = 0; j <= i - 1; j++){

// If current element is greater than next element, swap them
if(arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

int main(){

int n;
cout << "enter no:" << endl;
cin >> n; // Input size of array

int arr[n]; // Declare array of size n

// Input array elements
for(int i = 0; i < n; i++){
cin >> arr[i];
}

// Call bubble sort function
bubble_sort(arr, n);

// Print sorted array
for(int i = 0; i < n; i++){
cout << arr[i] << " ";
}

return 0; // Program ends successfully
}