Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Improved_Bubble_Sort.cpp #300

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 25 additions & 25 deletions Improved_Bubble_Sort.cpp
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
//Program : To sort a given array using an improved version of bubble sort which has a better time complexity.
#include<iostream>
using namespace std;
int main(void){

int main() {
int n;
cout<<"Enter Size of array: ";
cin>>n;
cout << "Enter Size of array: ";
cin >> n;
int arr[n];
cout<<"Enter elements in the array: ";
for(int i=0;i<n;i++){
cin>>arr[i];
cout << "Enter elements in the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
bool flag=false; //a flag that is set if an exchange is made after an entire pass over the array
for(int x=0; x<n; x++)
{
flag=false;
for(int y=0; y<n-1; y++)
{
if(arr[y]>arr[y+1])
{
swap(arr[y],arr[y+1]);
flag = true;

bool flag = true; // Initialize flag to true
for (int x = 0; x < n && flag; x++) { // Update loop condition
flag = false; // Reset flag for this iteration
for (int y = 0; y < n - 1; y++) {
if (arr[y] > arr[y + 1]) {
swap(arr[y], arr[y + 1]);
flag = true; // Set flag if a swap occurs
}
}
}
if(!flag){
break;
}
}
cout<<"Elements in array after sorting: "<<endl;
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";

cout << "Elements in array after sorting: " << endl;
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
}
cout << endl;

return 0;
}