Friday 14 September 2012

Program that implements the bubble sort method

Description: Bubble sort is the simplest and oldest sorting technique. This method takes two elements at a time. It compare these two elements. If first elements is less than second one, they are left undistrurbed. If the first element is greater then second one then they are swapped. The procedure continues with the next two elements goes and ends when all the elements are sorted.
                                                 But bubble sort is an inefficient algorithm. The order of bubble sort algorithm is O(n2).
Algorithm:
        i)Bubble Sort:

1. start
2. read the value of n
3. for i= 1 to n increment in steps of 1
            Read the value of ith element into array
4. call function to sort (bubble_sort(a,n))
5. for i= 1 to n increment in steps of 1
            print the value of ith element in the array
6. stop

BUBBLE SORT FUNCTION

1. start
2. initialise last to n
3. for i= 1 to n increment in steps of 1
      begin
4.         initialise ex to 0
5.         for i= 1 to last-1 increment in steps of 1
              begin
6.                     if k[i]>k[i+1] goto step 7 otherwise goto step 5
                        begin
7.                     assign k[i] to temp
                         assign k[i+1] to k[i]
                         assign  temp to k[i+1]
                         increment ex by 1
                        end-if
              end inner for loop
11.       if ex!=0
            assign last-1 to last
      end for loop
12. stop          



      Program:

#include<stdio.h>
main()
{
int i,j,t,a[5],n;
clrscr();
printf("enter the range of array:");
scanf("%d",&n);
printf("enter elements into array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
 if(a[i]>a[j])
 {
  t=a[i];
  a[i]=a[j];
  a[j]=t;
  }
  printf("the sorted order is:");
  for(i=0;i<n;i++)
  printf("\t%d",a[i]);
  getch();
}


Input/Output:
enter the range of array:3
enter elements into array:3
2
1
the sorted order is:    1       2       3

enter the range of array:5
enter elements into array:56
23
34
12
8
the sorted order is:    8       12      23      34      56

conclusion: The program is error free

VIVA QUESATIONS
1)  Define bubble sort ?
Ans: : Bubble sort is the simplest and oldest sorting technique. This method takes two elements at a time. It compare these two elements. If first elements is less than second one, they are left undistrurbed. If the first element is greater then second one then they are swapped. The procedure continues with the next two elements goes and ends when all the elements are sorted.
2) display the efficiency of bubble sort ?
Ans : O(n2)

No comments:

Post a Comment