Powered by Blogger.

Bubble sort.


Programming of bubble sort.. and algorithm for bubble sort.


Bubble Sort
Bubble sort is a simple and well-known sorting algorithm. It is used in practice once in a blue moon and its main application is to make an introduction to the sorting algorithms. Bubble sort belongs to O(n2) sorting algorithms, which makes it quite inefficient for sorting large data volumes. Bubble sort is stable and adaptive.


Algorithm

  1. Compare each pair of adjacent elements from the beginning of an array and, if they are in reversed order, swap them.
  2. If at least one swap has been done, repeat step 1.
You can imagine that on every step big bubbles float to the surface and stay there. At the step, when no bubble moves, sorting stops. Let us see an example of sorting an array to make the idea of bubble sort clearer.
Example. Sort {5, 1, 12, -5, 16} using bubble sort.
Bubble sort example

Complexity analysis

Average and worst case complexity of bubble sort is O(n2). Also, it makes O(n2) swaps in the worst case. Bubble sort is adaptive. It means that for almost sorted array it gives O(n) estimation. Avoid implementations, which don't check if the array is already sorted on every step (any swaps made). This check is necessary, in order to preserve adaptive property.

Turtles and rabbits

One more problem of bubble sort is that its running time badly depends on the initial order of the elements. Big elements (rabbits) go up fast, while small ones (turtles) go down very slow. This problem is solved in theCocktail sort.
Turtle example. Thought, array {2, 3, 4, 5, 1} is almost sorted, it takes O(n2) iterations to sort an array. Element {1} is a turtle.
Turtle example
Rabbit example. Array {6, 1, 2, 3, 4, 5} is almost sorted too, but it takes O(n) iterations to sort it. Element {6} is a rabbit. This example demonstrates adaptive property of the bubble sort.
Rabbit example

Program.


#include <stdio.h>
#include<conio.h>

void print(int arr[],int size)
{
int i;
  for(i=0;i<size;i++)
printf(" %d   ",arr[i]);
}

void bubble_sort(int array[], int size)
{
int temp, i, j;

for (i = 0; i < size; i++)
    { for (j = 0; j < i; j++)
{ if (array[i] < array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
 }
    }
}

int main()
{
int values[30], i,size;
clrscr();

printf("how many elements are there in the array");
scanf("%d",&size);
fflush(stdin);

printf("\nenter the elemnts");
for(i=0;i<size;i++)
      {
      scanf("%d",&values[i]);
      fflush(stdin);
       }

printf("\nthe elements you entered are");
print(values,size);

bubble_sort(values, size);
printf("\n Sorted list is as follows\n");

print(values,size);
getch();
}

Share on Google Plus

About Unknown

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment