Bubble sort(optimized)
#include<iostream>
using namespace std ;
int main(){
int n ;
cin >> n ;
int a[n];
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
for (int count = 0; count <= n-1; ++count) {
int flag = 0 ;
for (int i = 0; i <= n-2 ; ++i) {
if (a[i] > a[i+1]){
swap(a[i],a[i+1]) ;
flag = 1 ;
}
}
if (flag == 0){ //array is already sorted
break;
}
}
for (int i = 0; i < n; ++i) {
cout << a[i] << " ";
}
return 0;
}
Comments
Post a Comment