Friday, April 15, 2016

C program to sort an array using bubble sort using recursive technique

Problem Statement:- we can an array of some integers/float datatype and we need to sort that
array using bubble sort recursively.
Bubble Sort- in bubble what we do is compare first two elements and sort them in sequence and then compare element number two and three and sort them we countinue this upto last element and we get largest element in last position in our first pass in next pass what we do is continue to do above process for the n-1 elements and we get second largest element in its place as we continue out sort and in nth pass we get our list sorted.
Recursive - the function which calls itself

#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 813 77 90

No comments:

Post a Comment