mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
f499342869
-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.
47 lines
579 B
C++
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";
|
|
}
|
|
}
|