Bubble Sort (बबल सॉर्ट)

Bubble Sort (बबल सॉर्ट):-

It is the simplest sorting algorithm in which we repeatedly swap the adjacent elements (pair) if they are in wrong order. It means first of all first two elements compared and if they are in wrong order then they will be swapped now second and third element will compare if they are in wrong order then they will be swapped and this process will continue until the largest element is shifted to the end of the list. Now in next iteration, above process will continue for remaining elements of the list. 

यह सॉर्टिंग की सबसे सरल युक्ति है जिसमे सभी नज़दीकी एलेमेंट्स(युग्म) को उत्तरोत्तर स्वैप किया जाता है यदि उनका क्रम गलत है अर्थात सर्वप्रथम पहले दो एलेमेंट्स की तुलना की जाती है यदि वे गलत क्रम में व्यवस्थित है तब उन्हें स्वैप कर दिया जाता है अब दुसरे व् तीसरे एलिमेंट की तुलना की जाती है यदि वे गलत क्रम में व्यवस्थित है तब उन्हें भी स्वैप कर दिया जाता है यह प्रक्रिया तब तक चलती रहती है जब तक की सबसे बढ़ा एलिमेंट लिस्ट के अंत में ना पहुँच जाये। अब अगली पुनरावृत्ति में पुनः शेष एलेमेंट्स के लिए इसी प्रक्रिया को दोहराया जाता है।        

Algorithm/function/program for Bubble Sort:-

File Name:- bsort.cpp

#include<iostream.h>
#include<conio.h>
#define N 5
//bubble sort function
void bsort(){
int list[N],i,j,temp;
clrscr();
cout<<"Bubble Sort"<<endl<<"Enter elements of List"<<endl;
for(i=0;i<N;i++){
cout<<"Enter "<<endl<<i+1<<" element= ";
cin>>list[i];
}
cout<<"List before Sorting-"<<endl;
for(i=0;i<N;i++){
cout<<list[i]<<" ";
}
for(i=0;i<N;i++){
for(j=0;j<N-1-i;j++){
if(list[j]>list[j+1]){
temp=list[j];
list[j]=list[j+1];
list[j+1]=temp;
}}}
cout<<"List after Sorting-"<<endl;
for(i=0;i<N;i++){
cout<<list[i]<<" ";
}
}
void main(){
bsort();
getch();
}

File Name:- bsort.c

#include<stdio.h>
#include<conio.h>
#define N 5
//bubble sort function/algorithm
void bsort(){
int list[N],i,j,temp;
clrscr();
printf("Bubble Sort\n Enter elements of List\n");
for(i=0;i<N;i++){
printf("Enter %d element= ",i+1);
scanf("%d",&list[i]);
}
printf("List before Sorting-\n");
for(i=0;i<N;i++){
printf(" %d ",list[i]);
}
for(i=0;i<N;i++){
for(j=0;j<N-1-i;j++){
if(list[j]>list[j+1]){
temp=list[j];
list[j]=list[j+1];
list[j+1]=temp;
}}}
printf("\nList after Sorting-\n");
for(i=0;i<N;i++){
printf(" %d ",list[i]);
}
}
void main(){
bsort();
getch();
}

1 comment:

  1. Really nice blog, very infromative. You can refer more topics related to Data Structure like Sorting alorithm, Searching Algorithm and stack linked list from here for future articles
    Thanks !

    ReplyDelete

Stack Data Structure, Push, Pop and Peek Operations , Applications of Stack

Stack is a linear data structure. It is collection of ordered data elements. It is also known as LIFO system (last in first out). It means i...