Saturday 17 December 2011

Bubble sorting

Q. Write a program to accept 10 numbers from user and sort list using Bubble sorting method.

Ans.
Logic of bubble sorting as follows:


In bubble sorting steps:
1. Start from left hand side
2. Compare first two numbers
3. If first_number > second_number than swap both number position. And if first_number < second_number than these compare next two numbers i.e. second_number and third_number.
4. Step-3 process repeat until there are no more numbers left to compared.
5. Bubble sorting completed.

An example on bubble sort.
To understand logic of Bubble Sorting, lets take random numbers:

6  3  7  1  4  5  2

First iteration
6  3  7  1  4  5  2

6  7  1  4  5  2

3  6  7  1  4  5  2

3  6  1  7  4  5  2

3  6  1  4  7  5  2

3  6  1  4  5  7  2

3  6  1  4  5  2  7

Second iteration
3  6  1  4  5  2  7

6  1  4  5  2  7

3  1  6  4  5  2  7
3  1  4  6  5  2  7

3  1  4  5  6  2  7

3  1  4  5  2  6  7


Third iteration
3  1  4  5  2  6  7

3  4  5  2  6  7

1  3  4  5  2  6  7

1  3  4  5  2  6  7

1  3  4  2  5  6  7

Four iteration
1  3  4  2  5  6  7

3  4  2  5  6  7

4  2  5  6  7

1  3  2  4  5  6  7

Five iteration
1  3  4  5  6  7

3  2  4  5  6  7

1  2  3  4  5  6  7

Six iteration
1  2  3  4  5  6  7

2  3  4  5  6  7

Seven iteration
1  2  3  4  5  6  7

/*program to example of bubble sorting*/
#include<stdio.h>
#include<conio.h>
#define SIZE 7
int main()
{
 int i,j,temp;
 int arr[ SIZE ];
 for(i=0; i<SIZE; i++)
 {
  printf("Enter Number : ");
  scanf("%d",&arr[i]);
 }
 for(i=0; i<SIZE ; i++)
 {
   for(j=0; j<(SIZE-1)-i; j++)
   {
     if( arr[j] < arr[j+1] )
     {
        temp=arr[j];
        arr[j]=arr[j+1];
        arr[j+1]=temp;
     }
   }
   printf("%d\t",arr[j]);
 }
 getch();
 return 0;
}

Output:-
Enter number : 6
Enter number : 3
Enter number : 7
Enter number : 1
Enter number : 4
Enter number : 5
Enter number :  2
1  2  3  4  5  6  7

No comments:

Post a Comment