0% found this document useful (0 votes)
19 views8 pages

Aoa Exp 3

Uploaded by

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

Aoa Exp 3

Uploaded by

studyfocus99.99
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Name : Ibrahim Abdul Majeed Parkar

Roll No : 43

Experiment No. 3

Title : Implementation and analysis of Merge sort/ Quick sort algorithm


by using D & C.

Input : (Quick Sort)

#include<stdio.h>

//function to swap two integers

void swap(int a[],int i,int j)

int temp = a[i];

a[i]=a[j];

a[j]=temp;

//partition function for quicksort

int partition(int a[],int start,int end)

{
int pivot=a[end];//choosing the last element as pivot

int i=start-1;

for(int j=start;j<end;j++)

if(a[j]<pivot)

i++;

swap(a,i,j);

swap(a,i+1,end);

return i+1;

//quicksort fuction

void quicksort(int a[],int start,int end)

if(start<end)

int pi=partition(a,start,end);

quicksort(a,start,pi-1);
quicksort(a,pi+1,end);

//main function

int main()

int n,i;

int arr[100];//max size=100

printf("Enter number of elements");

scanf("%d",&n);

printf("Enter %d elements:\n",n);

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

scanf("%d",&arr[i]);

quicksort(arr,0,n-1);

printf("Sorted array :\n");

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

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

return 0;

Output :
Input : (Merge Sort)

#include <stdio.h>

// Function to print the array (one element per line)

void printArray(int arr[], int size) {

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

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

// Merge function

void merge(int arr[], int start, int mid, int end) {

int i, j, k;

int n1 = mid - start + 1;

int n2 = end - mid;

int L[n1], R[n2]; // Temporary arrays

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

L[i] = arr[start + i];

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

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

i = 0; // Index for L[]

j = 0; // Index for R[]

k = start; // Index for merged array


while (i < n1 && j < n2) {

if (L[i] <= R[j])

arr[k++] = L[i++];

else

arr[k++] = R[j++];

while (i < n1)

arr[k++] = L[i++];

while (j < n2)

arr[k++] = R[j++];

// Merge sort function

void mergeSort(int arr[], int start, int end) {

if (start < end) {

int mid = start + (end - start) / 2;

mergeSort(arr, start, mid);

mergeSort(arr, mid + 1, end);

merge(arr, start, mid, end);

}
// Main function

int main() {

int arr[100], n;

printf("Enter the number of elements: ");

scanf("%d", &n);

printf("Enter %d elements:\n", n);

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

scanf("%d", &arr[i]);

printf("Original array:\n");

printArray(arr, n);

mergeSort(arr, 0, n - 1);

printf("Sorted array:\n");

printArray(arr, n);

return 0;

}
Output:

You might also like