Bubble sort(sinking sort)
Bubble sort is a simple sorting algorithm. In this algorithm same process happens until the considering list become a sorted list. Throughout the sorting process compares each pair of adjacent items and adjust them one pair at a time.
Lets consider a list containing numbers to be sort
6,4,3,5,7
lets take first two numbers 6 & 4
6>4
because of that we have to adjust 6 & 4
new list : 4,6,3,5,7
then take second pair of numbers
6>3
after adjusting new list : 4,3,6,5,7
like this continue until the lat pair
4,3,5,6,7
4,3,5,6,7
after comparing last pair start same process from the beginning of the new list
3,4,5,6,7
after this step list becomes sorted.
Pseudo code implementation
begin Bubblesort(list)
temp == 0
for all
if list[i] > list[i+1]
temp == list [i+1]
list[i+1] == list[i]
list[i] = temp
end if
end for
return list
end Bubblesort
python implementation
def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
implementation using c
#include <stdio.h>
void bubble_sort(long [], long);
int main()
{
long array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%ld", &n);
printf("Enter %ld integers\n", n);
for (c = 0; c < n; c++)
scanf("%ld", &array[c]);
bubble_sort(array, n);
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%ld\n", array[c]);
return 0;
}
void bubble_sort(long list[], long n)
{
long c, d, t;
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (list[d] > list[d+1])
{
/* Swapping */
t = list[d];
list[d] = list[d+1];
list[d+1] = t;
}
}
}
}
No comments:
Post a Comment