BUBBLE SORTING TECHNIQUE

              BUBBLE SORT

               Bubble sorting is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements of the array.





Explanation:

  1. Outer for loop I iterate for n-1 times(because if n-1 elements are sorted then automatically the nth element gets sorted.)
  2. Inner for loop checks (n-i-1) times with condition if statement: the adjacent element greater or not.
  3. if YES then swap both the number.
  4. TO optimize the code use flag variable to optimize.
  5. if the elements are swapped then flag=1, of not then flag remains unchanged, so it breaks the outer for loop.


Code fo BUBBLE SORT IN CPP:


#include <iostream>
using namespace std;
int main()
{
    int i,j,n,flag,temp;
    int arr[100];
    cout<<"Enter size of the array:"<<endl;
    cin>>n;
    cout<<"Enter array that to be sorted by bubble sort"<<endl;
    for(i=0;i<n;i++){
        cin>>arr[i];
    }
    for(i=0;i<n-1;i++){
        flag=0;
        for(j=0;j<n-i-1;j++){
            if(arr[j+1]<arr[j]){
                temp=arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=temp;
                flag=1;
            }
        }
        if(flag==0){
            break;
        }
    }
    cout<<"Sorted Array is:"<<endl;
    for(i=0;i<n;i++){
        cout<<arr[i]<<" ";
    }
    return 0;
}

Comments

Popular posts from this blog

INSERTION SORTING