C program for bubble sort

Bubble sort in c: Bubble sort is the simplest algorithm for sorting elements of array. We can sort elements in ascending and descending order using bubble sort algorithm.

C program for ascending order:

#include<stdio.h>
 
int main()
{
 int n, arr[100], i, j, temp;
 
 printf("Enter number for elements: ");
 scanf("%d",&n);
 
 printf("Enter %d elements: \n",n);
 for(i=0;i<n;i++)
 {
  scanf("%d",&arr[i]);
 }
 
 for(i=0;i<n-1;i++)
 {
  for(j=0;j<n-1-i;j++)
  {
   if(arr[j]>arr[j+1])
   {
    temp=arr[j];
    arr[j]=arr[j+1];
    arr[j+1]=temp;
   }
  }
 }
 
 printf("Sorted array is \n");
 
 for(i=0;i<n;i++)
 {
  printf("%d ",arr[i]);
 }
 
 return 0;
}

C Program for descending order:

#include<stdio.h>
 
int main()
{
 int n, arr[100], i, j, temp;
 
 printf("Enter number for elements: ");
 scanf("%d",&n);
 
 printf("Enter %d elements: \n",n);
 for(i=0;i<n;i++)
 {
  scanf("%d",&arr[i]);
 }
 
 for(i=0;i<n-1;i++)
 {
  for(j=0;j<n-1-i;j++)
  {
   if(arr[j]<arr[j+1])
   {
    temp=arr[j];
    arr[j]=arr[j+1];
    arr[j+1]=temp;
   }
  }
 }
 
 printf("Sorted array is \n");
 
 for(i=0;i<n;i++)
 {
  printf("%d ",arr[i]);
 }
 
 return 0;
}





Popular posts from this blog