Saturday 21 September 2013

Saturday 21 September 2013

Program in c for BubbleSort


C program for Bubble Sort:

 The first member of the list is compared with the next element. To sort in ascending order we usually begin the process by checking if first element is greater than next element.
 If yes, we interchange their position accordingly. i.e first element is moved to second element’s position and second element is moved to first element’s position. 
If No, then we dont interchange any elements. As next step, the element in second position is compared with element in third position and the process of interchanging elements is performed if required. The whole process of comparing and interchanging is repeated till last element.
 When the process gets completed, the largest element in array will get placed in the last position of the list/array.

#include<stdio.h>
int main(){

  int s,temp,i,j,a[20];

  printf("Enter total numbers of elements: ");
  scanf("%d",&s);

  printf("Enter %d elements: ",s);
  for(i=0;i<s;i++)
      scanf("%d",&a[i]);

  //Bubble sorting algorithm
  for(i=0;i<s;i++){
      for(j=0;j<s;j++){
           if(a[j]>a[j+1]){
               temp=a[j];
              a[j]=a[j+1];
              a[j+1]=temp;
           }
      }
  }

  printf("After sorting:\n ");
  for(i=0;i<s;i++)
      printf(" %d",a[i]);

  return 0;
}

Compiling the source code....
$gcc main.c -o demo -lm -pthread -lgmp -lreadline 2>&1

Executing the program....
$demo
Enter total numbers of elements: Enter 6 elements:5 2 7 8 66 23
 After sorting:
  2 5 7 8 23 66

No comments:

Post a Comment