Quick Sort
Quick Sort
50 which is greater than pivot taken as i and the 20 smaller than pivot taken as j
Program:
#include<stdio.h>
void quicksort(int a[25],int first,int last)
{
int i, j, pivot, temp;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(a[i]<a[pivot]&&i<=last)
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];
a[j]=temp;
quicksort(a,first,j-1);
quicksort(a,j+1,last);
}
}
int main()
{
int i, n, a[25];
printf("Enter total a of elements:\n ");
scanf("%d",&n);
printf("Enter elements:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
quicksort(a,0,n-1);
printf("The Sorted elements are:\n ");
for(i=0;i<n;i++)
printf(" %d",a[i]);
return 0;
}
Merging or Merge Sort:
It divides input array into two halves, calls itself for the two halves and then sorted and
merged that two halves.
Example:
For example consider the array of elements: 38, 27, 43, 3, 9, 82, 10
Now the array is recursively divided into two halves till the size becomes one which is
shown in the following figure.
Once the size becomes one, the merge process comes into action and starts merging with
sorted array till the complete array is merged.
Algorithm:
Step 1 − If it is only one element in the list then it is already sorted.
Step 2 − Divide the list recursively into two halves till the size becomes one.
Step 3 − Once the size becomes 1, the merge process comes into action and starts
merging with sorted array till the complete array is merged.
Program:
#include<stdio.h>
int n,a[30],i,j,k,temp[30];
void merge(int low,int mid,int high)
{
i=low;
j=mid+1;
k=low;
while((i<=mid) && (j<=high))
{
if(a[i]>=a[j])
temp[k++]=a[j++];
else
temp[k++]=a[i++];
}
while(i<=mid)
temp[k++]=a[i++];
while(j<=high)
temp[k++]=a[j++];
for(i=low;i<=high;i++)
a[i]=temp[i];
}
void mergesort(int low,int high)
{
int mid;
if(low!=high)
{
mid=((low+high)/2);
mergesort(low,mid);
mergesort(mid+1,high);
merge(low,mid,high);
}
}
int main()
{
printf("Enter total elements:\n");
scanf("%d",&n);
printf("Enter elements:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(0,n-1);
printf("After sorting is:\n");
for(i=0;i<n;i++)
printf(" %d",a[i]);
return 0;
}
Time Complexity:
O(n^2) means that for every insert, it takes n*n operations. i.e. 1 operation for 1 item, 4
operations for 2 items, 9 operations for 3 items.