Unit 6
Unit 6
Unit 6
PREPARED BY
PROF. VISHVA UPADHYAY
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)
Ackerman function
#include<stdio.h>
int ack(int,int);
int main()
{
Int m,n;
printf(“enter the values of m and n:”);
scanf(“%d %d”,&m,&n);
ack(m,n);
printf(“The answer is %d”,ack(m,n));
return 0;
}
Output:
Enter the values of m & n: 0
2
The answer is 3
2
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)
Quick Sort:
It is a divide and conquer algorithm.
3
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)
return end
}
quicksort(a,lb,ub)
{
if(lb<ub)
{
loc = partition(a,lb,ub)
quicksort(a,lb,loc-1)
quicksort(a,loc+1,ub)
}
}
Program for Quick Sort
#include<stdio.h>
void quicksort(int a[40],int start,int end)
{
int i, j, pivot, temp;
if(start<end)
{
pivot=start;
i=start;
j=end;
while(i<j)
{
while(a[i]<=a[pivot]&&i<end)
i++;
while(a[j]>a[pivot])
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[pivot];
a[pivot]=a[j];
4
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)
a[j]=temp;
quicksort(a,start,j-1);
quicksort(a,j+1,end);
}
}
int main()
{
int i, n, a[40];
printf("Enter size of the array: ");
scanf("%d",&n);
printf("Enter %d elements: ", n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
quicksort(a,0,n-1);
printf("Order of Sorted elements: ");
for(i=0;i<n;i++)
printf(" %d",a[i]);
return 0;
}
Merge Sort
● Merge Sort is one of the best examples of Divide & Conquer algorithms.
● In Merge sort, we divide the array recursively in two halves, until each sub-array contains
a single element, and then we merge the sub-array in a way that it results into a sorted
array. merge() function merges two sorted sub-arrays into one, wherein it assumes that
array[lb .. n] and arr[n+1 .. ub] are sorted.
mergesort(a,lb,ub)
{
if(lb<ub)
5
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)
{
mid=(lb+ub)/2
mergesort(a,lb,mid)
mergesort(a,mid+1,ub)
merge(a,lb,mid,mid+1,ub)
}
}
merge(a,lb,mid,ub)
{
i=lb;
j=mid+1;
k=lb;
while(i<=mid && j<=ub)
{
if(a[i]<a[j])
{
b[k]=a[i]
i++
k++
}
else
{
b[k]=a[j]
j++
k++
}
if(i>mid)
{
while(j<=ub)
{
b[k]=a[j]
j++
k++
}
}
else
{
while(i<=mid)
{
6
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)
b[k]=a[i]
}
for(k=lb;k<=ub;k++)
{
a[k]=b[k]
}
}
}
Closing of merge
C Program for Merge Sort
#include<stdio.h>
void mergesort();
void merge();
int main()
{
int a[40],n,i;
printf("Enter array size:");
scanf("%d",&n);
7
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)
if(start<end)
{
mid=(start+end)/2;
mergesort(a,start,mid);
mergesort(a,mid+1,end);
merge(a,start,mid,end);
}
}
8
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)
}
else
{
while(i<=mid)
{
b[k]=a[i];
i++;
k++;
}
}
for(i=start;i<=end;i++)
{
a[i]=b[i];
}
}