Saturday 19 March 2016

BUBBLE SORT


Write a C program to perform bubble sort on an array of n elements.

Input Format: 
Input consists of n+1 integers. The first integer corresponds to n, the number of elements in the array. The next n integers correspond to the elements in the array.

Output Format: 
Refer sample output for formatting specs.

Sample Input and Output: 
[All text in bold corresponds to input and the rest corresponds to output]
Enter the number of elements :
5
Enter element 1
34
Enter element 2
23
Enter element 3
67
Enter element 4
34
Enter element 5
2
Unsorted list is :
34 23 67 34 2
After Pass 1 elements are :23 34 34 2 67
After Pass 2 elements are :23 34 2 34 67
After Pass 3 elements are :23 2 34 34 67
After Pass 4 elements are :2 23 34 34 67
Sorted list is :
2 23 34 34 67
 Note: stop the process if u find that the list is sorted in any intermediate point

Code:
  #include<stdio.h>
int main(){
  int n,a[20],i,temp,j,k,flag;
  printf("Enter the number of elements :\n");
  scanf("%d",&n);
  for(i=0;i<n;i++)
  {
    printf("Enter element %d\n",i+1);
    scanf("%d",&a[i]);
  }
  printf("Unsorted list is :\n");
  for(i=0;i<n;i++)
    printf("%d ",a[i]);
  for(i=0;i<n-1;i++)
  {
    flag=0;
    for(j=0;j<=n-2;j++)
    {
      if(a[j]>a[j+1])
      {
        temp=a[j];
        a[j]=a[j+1];
        a[j+1]=temp;
        flag++;
      }
    }
      printf("\nAfter Pass %d elements are :",i+1);
      for(k=0;k<n;k++)
        printf("%d ",a[k]);
    if(flag==0)
      break;
  }
  printf("\nSorted list is :\n");
  for(i=0;i<n;i++)
    printf("%d ",a[i]);
  return 0;
}
  

No comments:

Post a Comment