TheAlgorithms-C-Plus-Plus/Sorting/Bubble Sort.cpp
Vaibhav Gupta f499342869
Optimize bubble sort algorithm
-introduced variable 'swap' for 'outer-for-loop' of bubble sort algorithm. If it remains zero after executing inner-loop, it means array is sorted, hence it does not need to run for n^2 times.
- 'for(int j=0; j<n-1-i; j++)', as after each step, one number reaches to its right position. Thus inner loop does not need to run for 'n' times in every cycle.
2018-10-02 16:34:16 +05:30

47 lines
579 B
C++

//Bubble Sort
#include<iostream>
using namespace std;
int main()
{
int n;
short swap=0;
cin >> n;
int Array[n];
cout<<"\nEnter any "<<n<<" Numbers for Unsorted Array : ";
//Input
for(int i=0; i<n; i++)
{
cin>>Array[i];
}
//Bubble Sorting
for(int i=0; i<n; i++)
{
swap=0;
for(int j=0; j<n-1-i; j++)
{
if(Array[j]>Array[j+1])
{
swap=1;
int temp=Array[j];
Array[j]=Array[j+1];
Array[j+1]=temp;
}
}
if(swap == 0)
{
break;
}
}
//Output
cout<<"\nSorted Array : ";
for(int i=0; i<n; i++)
{
cout<<Array[i]<<"\t";
}
}