mirror of
https://github.com/TheAlgorithms/C-Plus-Plus.git
synced 2026-04-03 18:50:56 +08:00
Update Bubble Sort.cpp
reduced the number of iteration done be inner for loop used for sorting to improve efficiency.
This commit is contained in:
@@ -3,27 +3,24 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int n;
|
||||
int main(){
|
||||
int n, temp;
|
||||
cout<<"Enter size of Array = ";
|
||||
cin >> n;
|
||||
int Array[n];
|
||||
cout<<"\nEnter any 6 Numbers for Unsorted Array : ";
|
||||
int *Array = new int[n];
|
||||
cout<<"\nEnter any " <<n <<" Numbers for Unsorted Array :\n";
|
||||
|
||||
//Input
|
||||
for(int i=0; i<n; i++)
|
||||
{
|
||||
for(int i=0; i<n; i++){
|
||||
cout<<"value " <<(i+1) <<" = ";
|
||||
cin>>Array[i];
|
||||
}
|
||||
|
||||
//Bubble Sorting
|
||||
for(int i=0; i<n; i++)
|
||||
{
|
||||
for(int j=0; j<n-1; j++)
|
||||
{
|
||||
if(Array[j]>Array[j+1])
|
||||
{
|
||||
int temp=Array[j];
|
||||
for(int i=n; i>0; i--){
|
||||
for(int j=0; j<i; j++){ // Array[i..n] is already sorted
|
||||
if(Array[j]>Array[j+1]){
|
||||
temp=Array[j];
|
||||
Array[j]=Array[j+1];
|
||||
Array[j+1]=temp;
|
||||
}
|
||||
@@ -33,7 +30,6 @@ int main()
|
||||
//Output
|
||||
cout<<"\nSorted Array : ";
|
||||
for(int i=0; i<n; i++)
|
||||
{
|
||||
cout<<Array[i]<<"\t";
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user