From 703f0a538672b6e61fd9702fb7b313f66fe82aa5 Mon Sep 17 00:00:00 2001 From: shubham singla <43694495+shubhamsingla807@users.noreply.github.com> Date: Wed, 5 Oct 2022 15:19:49 +0530 Subject: [PATCH] Bubble sort --- C++/bubblesort.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 C++/bubblesort.cpp diff --git a/C++/bubblesort.cpp b/C++/bubblesort.cpp new file mode 100644 index 00000000..745bb058 --- /dev/null +++ b/C++/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; +}