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.
This commit is contained in:
Vaibhav Gupta 2018-10-02 16:34:16 +05:30 committed by GitHub
parent aead0ba366
commit f499342869
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -6,9 +6,10 @@ using namespace std;
int main()
{
int n;
short swap=0;
cin >> n;
int Array[n];
cout<<"\nEnter any 6 Numbers for Unsorted Array : ";
cout<<"\nEnter any "<<n<<" Numbers for Unsorted Array : ";
//Input
for(int i=0; i<n; i++)
@ -19,15 +20,21 @@ int main()
//Bubble Sorting
for(int i=0; i<n; i++)
{
for(int j=0; j<n-1; j++)
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