0% found this document useful (0 votes)
10 views4 pages

Exp 6

Uploaded by

HODCSE RKCE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views4 pages

Exp 6

Uploaded by

HODCSE RKCE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

EXPERIMENT-6

Implement Quick sort and Merge sort and observe the


execution time for various input sizes (Average, Worst and
Best cases).
// C program to implement Quick Sort Algorithm

#include <stdio.h>
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int low, int high)
{
int p = arr[low];
int i = low;
int j = high;
while (i < j)
{
while (arr[i] <= p && i <= high - 1)
{
i++;
}
while (arr[j] > p && j >= low + 1) {
j--;
}

if (i < j)
{
swap(&arr[i], &arr[j]);
}
}
swap(&arr[low], &arr[j]);
return j;
}
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);

// Recursively call quickSort() for left and right


// half based on Partition Index
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

int main() {

int arr[] = { 4, 2, 5, 3, 1 };
int n = sizeof(arr) / sizeof(arr[0]);

// calling quickSort() to sort the given array


quickSort(arr, 0, n - 1);

for (int i = 0; i < n; i++)


printf("%d ", arr[i]);

return 0;
}
Output:
4 7 11 12 13 15 16 18 19

// C program for the implementation of merge sort


#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
int leftArr[n1], rightArr[n2];

for (i = 0; i < n1; i++)

leftArr[i] = arr[left + i];

for (j = 0; j < n2; j++)

rightArr[j] = arr[mid + 1 + j];

i = 0;
j = 0;
k = left;
while (i < n1 && j < n2) {
if (leftArr[i] <= rightArr[j]) {
arr[k] = leftArr[i];
i++;
}
else {
arr[k] = rightArr[j];
j++;
}
k++;
}

while (i < n1) {


arr[k] = leftArr[i];
i++;
k++;
}

while (j < n2) {


arr[k] = rightArr[j];
j++;
k++;
}
}

void mergeSort(int arr[], int left, int right) {


if (left < right) {

// Calculate the midpoint


int mid = left + (right - left) / 2;

// Sort first and second halves


mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
int main() {
int arr[] = { 12, 11, 13, 5, 6, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, n - 1);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output
Given array is: 12 11 13 5 6 7
Sorted array is: 5 6 7 11 12 13

You might also like