cpp bubble sort
//HOW ABOUT MORE EFFICIENT SOLUTION // BASIC IDEA- REPEATEDLY SWAP TWO ADJACENT ELEMENTS IF THEY ARE IN A WRONG ORDER. #include<bits/stdc++.h> using namespace std; void bubblesort(int a[], int n) { bool swapped=false; for(int i=0;i<n-1;i++) { for(int j=0;j<n-i-1;j++) { if(a[j]>a[j+1]) // check if ADJACENT elements are in a wrong order. { swap(a[j],a[j+1]); //if they are swap them. swapped=true; } } if(swapped==false) break; // if for any particular iteration our array doesn't swap-- // -- any numbers then we may conclude that our array has already been sorted. :) } } int main() { int n; cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; bubblesort(a,n); for(int i=0;i<n;i++) cout<<a[i]<<" "; return 0; }
bubble sort in c+
#include <iostream> #include <iomanip> using namespace std; void sort (int array[],int size){ for(int i=0; i<size-1; i++){ for(int j=i+1; j<size; j++){ if(array[i] > array[j]){ int temp = array[j]; array[j] = array[i]; array[i] = temp; } } } cout<<"Sorted Array: \n"; for(int i=0;i<5;i++){ cout<<setw(5)<<array[i]; } } int main() { int array [5]; for(int i=0;i<5;i++){ cout<<"Element "<<i<<": "; cin>>array[i]; } sort(array,5); }
c++ code for bubble sort
#include<bits/stdc++.h> using namespace std; int main() { //bubble sort; int a[5]= {81,56,2,12,9}; bool flag = false; int i,j; //if(n>1) while(!flag) { flag = true; i=0; j=1; while(j<5) { if(a[i]>a[j]) { swap(a[i],a[j]); flag = false; } i++; j++; } } for(i=0;i<5;i++) { cout<<a[i]; } return 0; }
bubble sort c++
#include <bits/stdc++.h> using namespace std; int main (void) { int a[] = {5, 4, 3, 2, 1}, tempArr, i, j; for (i = 0; i < 5; i++) { for (j = i + 1; j < 5; j++) { if (a[j] < a[i]) { tempArr = a[i]; a[i] = a[j]; a[j] = tempArr; } } } for(i = 0; i < 5; i++) { cout<<a[i]<<"\n"; } return 0; }
bubble sort function in c++
void bubbleSort(int arr[], int n) { for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { if(arr[i]>arr[j]) { int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } }
Source: www.codegrepper.com