Showing posts with label bubble sort. Show all posts
Showing posts with label bubble sort. Show all posts

Friday, April 29, 2016

C program to sort array using bubble sort

#include<stdio.h>
#include<string.h>
void main()
{
 int a[10]={1,8,6,0,6,68,44,66,45,38};
 int i,temp,k,n=10;
 for(i=0;i<n;i++)
  {
   for(k=0;k<n-i-1;k++)
    {
     if(a[k]>a[k+1])
      {
       temp=a[k];
       a[k]=a[k+1];
       a[k+1]=temp;
      }
    }
  }
 for(i=0;i<n;i++)
  {
   printf("%d ",a[i]);
  }
}

output
0 1 6 6 8 38 44 45 66 68

Sunday, March 13, 2016

C program to implement bubble sort using recursion

#include<stdio.h>
#include<conio.h>
void sort(int arr_new[],int i,int n)
{
 int temp;
 if(i<n-1)
  {
   if(arr_new[i]>arr_new[i+1])
    {
     temp=arr_new[i];
     arr_new[i]=arr_new[i+1];
     arr_new[i+1]=temp;
    }
   sort(arr_new,++i,n);
   sort(arr_new,0,n-i);
  }
}
void main()
{
 clrscr();
 int arr[10]={3,8,7,6,0,77,3,90,3,13};
 int i;
 printf("Array elements before sorting");
 for(i=0;i<10;i++){
  printf(" %d",arr[i]);
 }
 sort(arr,0,10);
 printf("Array elements after sorting");
 for(i=0;i<10;i++)
  {
   printf(" %d",arr[i]);
  }
 getch();
}

output
Array elements before sorting
3 8 7 6 0 77 3 90 3 13
Array elements after sorting
0 3 3 3 6 7 8 13 77 90