Friday, November 19, 2021

simple program using Bubble sort in data structure

                                                  //bubble sort

#include<iostream>

using namespace std;

int main()

{

int n,temp,j,swap_counter=0,pass_counter=0,arr0_counter=0,comp_counter=0;

//here we enter the size of array

cout<<"Please Enter The Size Of Array:";

cin>>n;

int arr[n];

//here we enter the element in an array

cout<<"Please Enter Element in Array:";

//use loop for enter element in array

for(int i=0;i<n;i++) 

{

cin>>arr[i];

}

cout<<endl<<endl;

//print element of array before sorting

  cout<<"\t\tBefore Sorting"<<endl;

  cout<<"[";

  //use loop for print element 

  for(int i=0;i<n;i++)

  {

  cout<<arr[i]<<",";

}

cout<<"]";

for(int i=0;i<n-1;i++)  //Loop for number of passes

{

for(j=0;j<n-1-i;j++) //Loop for number of comparisons

{

comp_counter++; //here we count the number og comparision

if(j==0)

{

arr0_counter++; //here we count the number of array0 index

}

if(arr[j]>arr[j+1])

{

swap_counter++; //here we count the number of swaps

cout<<endl;

cout<<"At ["<<j<<"]index :"<<arr[j]<<endl;

cout<<"At ["<<j+1<<"]index :"<<arr[j+1]<<endl;

cout<<arr[j]<<" is greater than "<<arr[j+1]<<"so there will be swaping:"<<endl;

temp=arr[j];

arr[j]=arr[j+1];

arr[j+1]=temp;

cout<<"NOW"<<endl;

cout<<"at ["<<j<<"]index :"<<arr[j]<<endl;

cout<<"at ["<<j+1<<"]index :"<<arr[j+1]<<endl;

}

else

{

cout<<arr[j]<<" is less than "<<arr[j+1]<<"so there will be no swaping:"<<endl;

}

}

pass_counter++; //here we count the number of passes

}

cout<<"Number Of Swaps Are:"<<swap_counter<<endl;

cout<<"Number Of Passes Are:"<<pass_counter<<endl;

cout<<"Go To 0 Index For "<<arr0_counter<<" times"<<endl;

cout<<"Number Of Comparison:"<<comp_counter<<endl;

cout<<endl<<endl;

//print element of array after sorting

cout<<"\t\tAfter Sorting"<<endl;

  cout<<"[";

  //use loop for print element 

  for(int i=0;i<n;i++)

  {

  cout<<arr[i]<<",";

}

cout<<"]";

}

No comments:

Post a Comment