From 627b8aa8fa4fd8ab031cc5c1b0a3a0e076e36dc8 Mon Sep 17 00:00:00 2001 From: AnishKr91620 <145275076+AnishKr91620@users.noreply.github.com> Date: Wed, 11 Oct 2023 22:28:12 +0530 Subject: [PATCH] Create bubble-sort Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high. --- bubble-sort | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 bubble-sort diff --git a/bubble-sort b/bubble-sort new file mode 100644 index 0000000..354af29 --- /dev/null +++ b/bubble-sort @@ -0,0 +1,44 @@ +// Optimized implementation of Bubble sort +#include +using namespace std; + +// An optimized version of Bubble Sort +void bubbleSort(int arr[], int n) +{ + int i, j; + bool swapped; + for (i = 0; i < n - 1; i++) { + swapped = false; + for (j = 0; j < n - i - 1; j++) { + if (arr[j] > arr[j + 1]) { + swap(arr[j], arr[j + 1]); + swapped = true; + } + } + + // If no two elements were swapped + // by inner loop, then break + if (swapped == false) + break; + } +} + +// Function to print an array +void printArray(int arr[], int size) +{ + int i; + for (i = 0; i < size; i++) + cout << " " << arr[i]; +} + +// Driver program to test above functions +int main() +{ + int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; + int N = sizeof(arr) / sizeof(arr[0]); + bubbleSort(arr, N); + cout << "Sorted array: \n"; + printArray(arr, N); + return 0; +} +// This code is contributed by shivanisinghss2110