You are on page 1of 3

QUICKSORT PROGRAM

#include<stdio.h>
int Partition(int a[],int low,int high)
{
int i = low,j = high;
int pivot = a[low],temp;
while(i < j)
{
while(a[i] <= pivot && i <= high)
i = i + 1;
while(a[j] > pivot)
j = j - 1;
if(i < j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
a[low] = a[j];
a[j] = pivot;
return j;
}
void quicksort(int a[],int low, int high)
{
int j,l = low,h = high;
if(low < high)
{
j = Partition(a, l, h);
quicksort(a, l, j-1);
quicksort(a, j+1, h);
}
}
void main()
{
int low = 0,high = 10, i;
int a[10]= {9,0,8,1,7,2,6,3,4,5};
clrscr();
printf("given array elements:\n");
for(i = 0;i < high;i++)
printf("%d ",a[i]);
quicksort(a,low, high-1);
printf("\narray sorted by quick sort:\n");
for(i=0;i < high;i++)
printf("%d ",a[i]);
getch();
}

MERGE SORT PROGRAM


#include<stdio.h>
#include<conio.h>
#define MAX_SIZE 10
void merge_sort(int, int);
void merge_array(int, int, int, int);
int arr_sort[MAX_SIZE];
void main()
{
int i;
clrscr();
printf("Simple Merge Sort Example - Functions and Array\n");
printf("\nEnter %d Elements for Sorting\n", MAX_SIZE);
for (i = 0; i < MAX_SIZE; i++)
scanf("%d", &arr_sort[i]);
printf("\nYour Data :\n");
for (i = 0; i < MAX_SIZE; i++) {
printf("\t%d", arr_sort[i]);
}
merge_sort(0, MAX_SIZE - 1);

printf("\n\nSorted Data :\n");


for (i = 0; i < MAX_SIZE; i++) {
printf("\t%d", arr_sort[i]);
}
getch();
}
void merge_sort(int i, int j)
{
int m;
if (i < j)
{
m = (i + j) / 2;
merge_sort(i, m);
merge_sort(m + 1, j);
// Merging two arrays
merge_array(i, m, m + 1, j);
}
}

void merge_array(int a, int b, int c, int d)


{
int t[50];
int i = a, j = c, k = 0;

while (i <= b && j <= d)


{
if (arr_sort[i] < arr_sort[j])
t[k++] = arr_sort[i++];
else
t[k++] = arr_sort[j++];
}

//collect remaining elements


while (i <= b)
t[k++] = arr_sort[i++];

while (j <= d)
t[k++] = arr_sort[j++];

for (i = a, j = 0; i <= d; i++, j++)


arr_sort[i] = t[j];
}

Protect pdf from copying with Online-PDF-No-Copy.com

You might also like