mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
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:
parent
aead0ba366
commit
f499342869
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user