Created
January 30, 2013 22:03
-
-
Save vikashvverma/4677576 to your computer and use it in GitHub Desktop.
Bubble Sort
It’s a sorting algorithm, in which each pair of adjacent items are compared and swapped if they are in wrong order. The comparison is repeated until no swaps are needed, indicating that the list is sorted. The smaller elements ‘bubble’ to the top of the list, hence, the name Bubble Sort. In this like selection sort, after every pass …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
/* Logic : Do the following thing until the list is sorted | |
(i) Compare two adjacent elements and check if they are in correct order(that is second one has | |
to be greater than the first). | |
(ii) Swap them if they are not in correct order. | |
*/ | |
void BubbleSort(int *array,int number_of_elements) | |
{ | |
int iter, temp, swapped; | |
do | |
{ | |
swapped = 0; /* If no element is swapped array is sorted */ | |
/* In the following loop compare every pair of adjacent elements and check | |
if they are in correct order */ | |
for(iter = 1; iter < number_of_elements; iter++) | |
{ | |
if(array[iter-1] > array[iter]) | |
{ | |
temp = array[iter-1]; | |
array[iter-1] = array[iter]; | |
array[iter] = temp; | |
swapped = 1; | |
} | |
} | |
}while(swapped); | |
} | |
int main() | |
{ | |
int number_of_elements; | |
scanf("%d",&number_of_elements); | |
int array[number_of_elements]; | |
int iter; | |
for(iter = 0;iter < number_of_elements;iter++) | |
{ | |
scanf("%d",&array[iter]); | |
} | |
/* Calling this functions sorts the array */ | |
BubbleSort(array,number_of_elements); | |
for(iter = 0;iter < number_of_elements;iter++) | |
{ | |
printf("%d ",array[iter]); | |
} | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment