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
48 changes: 48 additions & 0 deletions sorting-algorithms/bubble_sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#include <iostream>
using namespace std;

/*
* BubbleSort:
* sorting algorithm that works by repeatedly swapping the adjacent elements
* if they are in wrong order
*
* Average/Worst Case Time Complexity: O(n*n)
* Best Case Time Complexity: O(n)
*/

// change location of two arrays
void swap(int &a, int &b) {
int tmp;
tmp = a;
a = b;
b = tmp;
}

// sort array in ascending order
void BubbleSort(int arr[], int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size-i-1; j++) {
if (arr[j] > arr[j + 1])
swap(arr[j], arr[j + 1]);
}
}
}

int main(){
int size;
int* array;
cout << "Size: ";
cin >> size;
array = new int[size];
for(int i=0;i<size;i++){
cout << "Array[" << (i+1) << "]: ";
cin >> array[i];
}
BubbleSort(array, size);
for(int j=0;j<size;j++){
cout << array[j] << " ";
}
return 0;
}