C प्रोग्रामिंग भाषा में, बबल सॉर्टिंग सबसे सरल सॉर्टिंग तकनीक है और इसे एक्सचेंज सॉर्ट भी कहा जाता है।
बबल सॉर्ट करने की प्रक्रिया
-
सूची में शेष तत्वों के साथ पहले तत्व की तुलना करें और यदि वे क्रम में नहीं हैं, तो उन्हें एक्सचेंज (स्वैप) करें।
-
सूची में अन्य तत्वों के लिए इसे तब तक दोहराएं जब तक कि सभी तत्व क्रमबद्ध न हो जाएं।
एल्गोरिदम
बबल सॉर्ट तकनीक का उपयोग करके संख्याओं की दी गई सूची को आरोही क्रम में क्रमबद्ध करने के लिए नीचे एक एल्गोरिथ्म दिया गया है -
चरण 1 - प्रारंभ करें
चरण 2 - सूची (सरणी), संख्या लें
चरण 3 - पठन सूची (सूची, संख्या)
चरण 4 - प्रिंटलिस्ट (सूची, संख्या)
चरण 5 -bub_sort(सूची,संख्या)
चरण 6 - प्रिंटलिस्ट (सूची, संख्या)
readlist (list, num)
चरण 7 - रुकें
1. for j = 0 to num 2. read list[j].
प्रिंटलिस्ट (सूची, संख्या)
1. for j =0 to num 2. write list[j].
bub_sort(सूची,संख्या)
1. for i = 0 to num 2. for j =0 to (num – i) 3. if( list[j] > list[j+1]) 4. swapList( address of list[j], address of list[j+1])
स्वैपलिस्ट (सूची का पता [जे], सूची का पता [जे + 1])
1. temp = value at list[j] 2. value at list[j] = value at list[j+1] 3. value at list[j+1] = temp
उदाहरण
बबल सॉर्ट तकनीक का उपयोग करके संख्याओं की दी गई सूची को आरोही क्रम में क्रमबद्ध करने के लिए C प्रोग्राम निम्नलिखित है -
#include <stdio.h>
#define MAX 10
void swapList(int *m,int *n){
int temp;
temp = *m;
*m = *n;
*n = temp;
}
/* Function for Bubble Sort */
void bub_sort(int list[], int n){
int i,j;
for(i=0;i<(n-1);i++)
for(j=0;j<(n-(i+1));j++)
if(list[j] > list[j+1])
swapList(&list[j],&list[j+1]);
}
void readlist(int list[],int n){
int j;
printf("\nEnter the elements: \n");
for(j=0;j<n;j++)
scanf("%d",&list[j]);
}
/* Showing the contents of the list */
void printlist(int list[],int n){
int j;
for(j=0;j<n;j++)
printf("%d\t",list[j]);
}
void main(){
int list[MAX], num;
printf(" Enter the number of elements \n");
scanf("%d",&num);
readlist(list,num);
printf("\n\nElements in the list before sorting are:\n");
printlist(list,num);
bub_sort(list,num);
printf("\n\nElements in the list after sorting are:\n");
printlist(list,num);
}
आउटपुट
जब उपरोक्त प्रोग्राम को निष्पादित किया जाता है, तो यह निम्नलिखित परिणाम उत्पन्न करता है -
Enter the number of elements 10 Enter the elements: 11 23 45 1 3 6 35 69 10 22 Elements in the list before sorting are: 11 23 45 1 3 6 35 69 10 22 Elements in the list after sorting are: 1 3 6 10 11 22 23 35 45 69