From 97f241852691305e4e7d02bddb7a53d0c2298a01 Mon Sep 17 00:00:00 2001 From: Roshan Agarwal <56463926+coolster9988@users.noreply.github.com> Date: Mon, 31 Oct 2022 23:00:16 +0530 Subject: [PATCH] Create BubbleSort.cpp --- BubbleSort.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 BubbleSort.cpp diff --git a/BubbleSort.cpp b/BubbleSort.cpp new file mode 100644 index 00000000..d7597487 --- /dev/null +++ b/BubbleSort.cpp @@ -0,0 +1,37 @@ +// C++ program for implementation +// of Bubble sort +#include +using namespace std; + +// A function to implement bubble sort +void bubbleSort(int arr[], int n) +{ + int i, j; + for (i = 0; i < n - 1; i++) + + // Last i elements are already + // in place + for (j = 0; j < n - i - 1; j++) + if (arr[j] > arr[j + 1]) + swap(arr[j], arr[j + 1]); +} + +// Function to print an array +void printArray(int arr[], int size) +{ + int i; + for (i = 0; i < size; i++) + cout << arr[i] << " "; + cout << endl; +} + +// Driver code +int main() +{ + int arr[] = { 5, 1, 4, 2, 8}; + int N = sizeof(arr) / sizeof(arr[0]); + bubbleSort(arr, N); + cout << "Sorted array: \n"; + printArray(arr, N); + return 0; +}