From ada02c2b40af83a44ff29ea9c73a4284497f9e21 Mon Sep 17 00:00:00 2001 From: Rahul Rajeev Pillai <66192267+Ashborn-SM@users.noreply.github.com> Date: Sat, 15 May 2021 23:44:44 +0530 Subject: [PATCH] enh(CPlusPlus): bubble-sort (#302) * Add binary-search-tree * Optimize the bubble sort * Revert "Add binary-search-tree" This reverts commit 8d712e7dcbae85d434775d7aaa53c9782e3d54b1. --- algorithms/CPlusPlus/Sorting/bubble-sort.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/algorithms/CPlusPlus/Sorting/bubble-sort.cpp b/algorithms/CPlusPlus/Sorting/bubble-sort.cpp index 8997f336..e8cf0c59 100644 --- a/algorithms/CPlusPlus/Sorting/bubble-sort.cpp +++ b/algorithms/CPlusPlus/Sorting/bubble-sort.cpp @@ -13,8 +13,10 @@ int main() { //array elements input cin>>arr[i]; } + bool swap; for (int i = 0; i < n; i++) { + swap = false; for (int j= 0; j< n-1; j++) { //comparing adjecent elements of array if (arr[j]>arr[j+1]) @@ -22,8 +24,13 @@ int main() temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; + swap = true; } } + + // break if no swap takes place in inner loop + // it means the array is sorted + if(!swap){ break; } } for (int i = 0; i < n; ++i) {