Thursday 18 November 2010

wap to bubble sort

1. wap to bubble sort.
algorithm:
1. compare the first two elements in the array, a[0], and a[1], if a[1] is smaller than a[0] then interchange(SWAP) their values.
2. compare a[1] and a[2]; interchange them if a[2] is smaller than a[1]. in general if(a[i]>a[i+1])
3. continue this process till the last two elements are compared and interchanged.
4. repeat the above steps n-1 times.



#include<stdio.h>
#include<conio.h>
void main()
{
 int a[10];
 int i,j,temp,n;
 clrscr();
 printf("enter the size of an array\n");
 scanf("%d",&n);
 printf("enter the values %d into array\n",n);
 for(i=0;i<=n-1;i++)
 {
  scanf("%d",&a[i]);
 }
 //sorting logic
 for(i=0;i<=n-1;i++)
 {
  for(j=i+1;j<=n-1;j++)
  {
   if(a[i]>a[j]){
   temp=a[i];
   a[i]=a[j];
   a[j]=temp;
   }
  }
 }
 for(i=0;i<=n-1;i++)
  printf("%d\n",a[i]);
  getch();
 }

More Explanation on Bubble Sort:


In a list with n elements, we need up to n-1 sort passes to order the list. With each sort pass, we increase the size of the sorted list by one (and decrease the size of the unsorted list by one).The algorithm finds the smallest value in the unsorted list and moves it to the next available position in the sorted list. Then, the barrier moves. In a bubble sort, the algorithm divides a list into two sub-lists – one sorted and one unsorted. An imaginary barrier separates the two lists.




You may like the following posts:

Arrays


No comments:

Post a Comment