diff --git a/loops/sorting/bubble_sort.cpp b/loops/sorting/bubble_sort.cpp new file mode 100644 index 0000000..cbb09c1 --- /dev/null +++ b/loops/sorting/bubble_sort.cpp @@ -0,0 +1,40 @@ +#include +using namespace std; + + +void printArray(int arr[], int n) { + for (int i = 0; i < n; i++) { + cout << arr[i] << " "; + } + cout << endl; +} + +// Bubble Sort function +// arr[] = input array, n = array size +void bubbleSort(int arr[], int n) { + + for (int i = 0; i < n - 1; i++) { + + for (int j = 0; j < n - i - 1; j++) { + + if (arr[j] > arr[j + 1]) { + swap(arr[j], arr[j + 1]); + } + } + } +} + +int main() { + int arr[] = {64, 34, 25, 12, 22, 11, 90}; + int n = sizeof(arr) / sizeof(arr[0]); + + cout << "Before sorting: "; + printArray(arr, n); + + bubbleSort(arr, n); + + cout << "After sorting: "; + printArray(arr, n); + + return 0; +}