Desing and Analysis of Alogorithm

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

HINDUSTAN COLLEGE OF SCIENCE

AND TECHNOLOGY
FARAH, MATHURA

Department of Computer Science and Engineering

Design and Analysis of Algorithms Lab

KCS-553

Submitted By- Submitted To-

Ekansh Kulshrestha Miss. Manisha Verma


(2000640100045) (Associate Professor)

1
INDEX:-

Teacher’s
S.No. List of Experiments:- Date Signature
WAP to sort an array using Selection 20/09/2022
1. sort
Wap to sort an array using Insertion 20/09/2022
2. sort
Wap to sort an array using Quick 11/10/2022
3. sort
Wap to sort an array using Bubble 11/10/2022
4. sort
Wap to sort an array using Merge 18/10/2022
5. sort.

Wap to sort an array using Heap 15/11/2022


6. sort.
Wap to sort an array using Radix 15/11/2022
7. sort
Wap to sort an array using Bucket 22/11/2022
8. sort

Wap to sort an array using Counting 22/11/2022


9. sort

Implementation of tree traversal. 06/12/2022


10.

2
Program-1

Aim - WAP to sort an array using Selection sort.

Algorithm:
1. Set min to the first location.

2. Search the minimum element in the array.

3. Swap the first location with the minimum value in the array.
4. Assign the second element as min.

5. Repeat the process until we get a sorted array.

Selection Sort Implementation in C -

#include <stdio.h>
int main()
{
int a[100], n, i, j, position, swap;
printf("Enter number of elements:");
scanf("%d", &n);
printf("Enter %d Numbers:", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for(i = 0; i < n - 1; i++)
{
position=i;
for(j = i + 1; j < n; j++)
{

if(a[position] > a[j]){


position=j;
}

3
if(position != i)
{
swap=a[i];
a[i]=a[position];
a[position]=swap;
}
}
printf("Sorted Array:\n");
for(i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}

4
Program-2

Aim - WAP to sort an array using Insertion sort.

Algorithm:-
1. The first element in the array is assumed to be sorted. Take the
second element and store it separately in key. Compare the key
with the first element. If the first element is greater than the key,
then the key is placed in front of the first element.
2. Now, the first two elements are sorted. Take the third element
and compare it with the elements on the left of it. Place it just
behind the element smaller than it. If there is no element smaller
then place it at the beginning of the array.
3. Similarly, place every unsorted element at its correct position.

Insertion sort Implementation in C-

#include <stdio.h>
// Function to print an array
void printArray(int array[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
}
void insertionSort(int array[], int size) {
for (int step = 1; step < size; step++) {
int key = array[step];
int j = step - 1;

// Compare key with each element on the left of it until an element


smaller than
// it is found.

5
// For descending order, change key<array[j] to key>array[j].
while (key < array[j] && j >= 0) {
array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
}
}
// Driver code
int main() {
int data[] = {9, 5, 1, 4, 3};
printf("Unsorted array:\n");
int size = sizeof(data) / sizeof(data[0]);
printArray(data,size);
insertionSort(data, size);
printf("Sorted array :\n");
printArray(data, size);
}

6
Program-3

Aim - WAP to sort an array by using Quick sort.

Algorithm:
Quicksort is a divide and conquer algorithm. It divides the large
array into smaller sub-arrays. And then quicksort recursively
sort the sub-arrays.
Pivot-
1. Pick an element called the “pivot” element.
Partition-

2. Rearrange the array elements in such a way that all values


lesser than the pivot should come before the pivot and all
the values greater than the pivot should come after it.

This method is called partitioning the array. At the end of the


partition function, the pivot elements will be placed at its sorted
position.
Recursive-

3. Do the above process recursively to all the sub-arrays and


sort the elements.
Base Case-

If the array has zero or one element, there is no need to call the
partition method. So we need to stop the recursive call when the
array size is less than or equal to 1.

7
Quick sort Implementation in C:

#include<stdio.h>

void quickSort(int[], int, int);


int partition(int[], int, int);
void swap(int*, int*);

int main()
{
int n,i;

printf("Enter Array Size\n");


scanf("%d",&n);

int arr[n];

printf("Enter Array Elements\n");


for(i=0;i<n;i++)
scanf("%d",&arr[i]);

quickSort(arr,0,n-1);

printf("After the QuickSort\n");

for(i=0;i<n;i++)
printf("%d ",arr[i]);
printf("\n");

return 0;
}

void quickSort(int arr[], int start, int end)


{

if(start < end)


{

8
int pIndex = partition(arr, start, end);
quickSort(arr, start, pIndex-1);
quickSort(arr, pIndex+1, end);
}
}

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


{
int pIndex = start;
int pivot = arr[end];
int i;
for(i = start; i < end; i++)
{
if(arr[i] < pivot)
{
swap(&arr[i], &arr[pIndex]);
pIndex++;
}
}
swap(&arr[end], &arr[pIndex]);
return pIndex;
}

void swap(int *x, int *y)


{
int t = *x;
*x = *y;
*y = t;
}

9
Program-4

Aim - WAP to sort an array by using Bubble sort.

Algorithm:
Suppose we are trying to sort the elements in ascending order.
1. First Iteration (Compare and Swap) Starting from the first index,
compare the first and the second elements. If the first element is
greater than the second element, they are swapped.
Now, compare the second and the third elements. Swap them if
they are not in order.
The above process goes on until the last element.
2. Remaining Iteration
The same process goes on for the remaining iterations. After
each iteration, the largest element among the unsorted elements
is placed at the end.

Implementation of Bubble Sort in C :

#include <stdio.h>

// perform the bubble sort


void bubbleSort(int array[], int size) {

// loop to access each array element


for (int step = 0; step < size - 1; ++step) {

// loop to compare array elements


for (int i = 0; i < size - step - 1; ++i) {
// compare two adjacent elements
// change > to < to sort in descending order

10
if (array[i] > array[i + 1]) {

// swapping occurs if elements


// are not in the intended order
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}

// print array
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}

int main() {
int data[] = {-2, 45, 0, 11, -9};

// find the array's length


int size = sizeof(data) / sizeof(data[0]);
printf("Unsorted Array:\n");
printArray(data, size);
bubbleSort(data, size);
printf("Sorted Array:\n");
printArray(data, size);
}

11
Program-5

Aim - WAP to sort an array using Merge Sort.

Algorithm:
MergeSort(arr[], l, r), where l is the index of the first element & r is
the index of the last element.
If r > l
1. Find the middle index of the array to divide it in two halves:
m = (l+r)/2
2. Call MergeSort for first half: mergeSort(array, l, m)
3. Call mergeSort for second half: mergeSort(array, m+1, r)
4. Recursively, merge the two halves in a sorted manner, so that
only one sorted array is left: merge(array, l, m, r)

Merge sort Implementation in C:

#include <stdio.h>
void printArray(int *A, int n)
{
for (int i = 0; i < n; i++)
{
printf("%d ", A[i]);
}
printf("\n");
}

void merge(int A[], int mid, int low, int high)


{
int i, j, k, B[100];

12
i = low;
j = mid + 1;
k = low;
while (i <= mid && j <= high)
{
if (A[i] < A[j])
{
B[k] = A[i];
i++;
k++;
}
else
{
B[k] = A[j];
j++;
k++;
}
}
while (i <= mid)
{
B[k] = A[i];
k++;
i++;
}
while (j <= high)
{
B[k] = A[j];
k++;
j++;
}
for (int i = low; i <= high; i++)
{
A[i] = B[i];
}
}

void mergeSort(int A[], int low, int high){


int mid;
if(low<high){

13
mid = (low + high) /2;
mergeSort(A, low, mid);
mergeSort(A, mid+1, high);
merge(A, mid, low, high);
}
}
int main()
{
// int A[] = {9, 14, 4, 8, 7, 5, 6};
int A[] = {9, 1, 4, 14, 4, 15, 6};
int n = 7;
printf("Unsorted array:\n");
printArray(A, n);
mergeSort(A, 0, 6);
printf("Sorted array:\n");
printArray(A, n);
return 0;
}

14
Program-6

Aim - WAP to sort an array using Heap Sort.

Algorithm:
1. Construct a Binary Tree with a given list of Elements.
2. Transform the Binary Tree into Min Heap.
3. Delete the root element from Min Heap using Heapify method.
4. Put the deleted element into the Sorted list.
5. Repeat the same until Min Heap becomes empty.
6. Display the sorted list.

Heap sort Implementation in C:

#include <stdio.h>

// Function to swap the the position of two elements


void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

void heapify(int arr[], int n, int i) {


// Find largest among root, left child and right child
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && arr[left] > arr[largest])

15
largest = left;

if (right < n && arr[right] > arr[largest])


largest = right;

// Swap and continue heapifying if root is not largest


if (largest != i) {
swap(&arr[i], &arr[largest]);
heapify(arr, n, largest);
}
}

// Main function to do heap sort


void heapSort(int arr[], int n) {
// Build max heap
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);

// Heap sort
for (int i = n - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);

// Heapify root element to get highest element at root again


heapify(arr, i, 0);
}
}

// Print an array
void printArray(int arr[], int n) {
for (int i = 0; i < n; ++i)
printf("%d ", arr[i]);
printf("\n");
}

16
// Driver code
int main() {
int arr[] = {1, 12, 9, 5, 6, 10};

int n = sizeof(arr) / sizeof(arr[0]);


printf("Unsorted array:\n");
printArray(arr, n);
heapSort(arr, n);
printf("Sorted array is \n");
printArray(arr, n);
}

17
Program- 7

Aim - WAP to sort an array using Radix sort.

Algorithm:
1. Identify the element with the maximum value in the list. In this
case, it is 835.
2. Calculate the number of digits of the maximum element. 835 has
3 digits exactly.
3. Determine the number of iterations based on step 2. 835 has 3
digits, meaning the number of iterations will be 3.
4. Determine the base of the elements. Since this is a decimal
system, the base will be 10.
5. Start with the first iteration:
a. First iteration- In the first iteration, we consider the unit place
value of each element.
b. Second iteration- In this iteration, we will consider the digit at
the 10th place for the sorting process.
c. Third iteration- For the final iteration, we want to get the most
significant digit. In this case, it’s the 100th place for each of
the integers in the list.

18
Radix sort Implementation in C:

#include <stdio.h>
#include <stdlib.h>
int getMax(int list[], int n) {
int mx = list[0];
int i;
for (i = 1; i < n; i++){
if (list[i] > mx)
mx = list[i];
}
return mx;
}
void countSort(int list[], int n, int exp) {
int output[n];
int i, count[10] = { 0 };
for (i = 0; i < n; i++)
count[(list[i] / exp) % 10]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--) {
output[count[(list[i] / exp) % 10] - 1] = list[i];
count[(list[i] / exp) % 10]--;
}
for (i = 0; i < n; i++)
list[i] = output[i];
}
void radixsort(int list[], int n) {
int m = getMax(list, n);
int exp;
for (exp = 1; m / exp > 0; exp *= 10)
countSort(list, n, exp);
}
void print(int list[], int n) {
int i;
for (i = 0; i < n; i++)
printf("%d\t", list[i]);
}

19
int main()
{
int list[] = { 82, 901, 100, 12, 150, 77, 55, 23 };
int i, n = sizeof(list) / sizeof(list[0]);
printf("List of numbers before sort: \n");
for(i = 0; i<8; i++)
printf("%d\t", list[i] );
radixsort(list, n);
printf("\n\nList of numbers after sort: \n");
print(list, n);
printf("\n\n");
return 0;
}

20
Program- 8

Aim - WAP to sort an array using Radix sort.

Algorithm:
1. Create B* buckets, each initialized with zero values.
2. Assign the range of elements that each bucket can hold.
3. Scatter: Find the range each element belongs to and put each
element into the bucket meant for its range
4. Sort: Iterate through all buckets and sort elements within each
bucket.
5. Gather the sorted elements from each bucket.
6. While gathering from the sorted buckets in the right order and
joining them, we know that we have sorted the elements fully
since bucket-level sorting (i.e., inter-bucket sorting) was already
done when we put elements in the bucket!

Bucket sort Implementation in C:

#include <stdio.h>
#include <stdlib.h>
#define NARRAY 7 // Array size
#define NBUCKET 6 // Number of buckets
#define INTERVAL 10 // Each bucket capacity
struct Node {
int data;
struct Node *next;
};
void BucketSort(int arr[]);
struct Node *InsertionSort(struct Node *list);

void print(int arr[]);

21
void printBuckets(struct Node *list);
int getBucketIndex(int value);
// Sorting function
void BucketSort(int arr[]) {
int i, j;
struct Node **buckets;
// Create buckets and allocate memory size
buckets = (struct Node **)malloc(sizeof(struct Node *) * NBUCKET);
// Initialize empty buckets
for (i = 0; i < NBUCKET; ++i) {
buckets[i] = NULL;
}
// Fill the buckets with respective elements
for (i = 0; i < NARRAY; ++i) {
struct Node *current;
int pos = getBucketIndex(arr[i]);
current = (struct Node *)malloc(sizeof(struct Node));
current->data = arr[i];
current->next = buckets[pos];
buckets[pos] = current;
}
// Print the buckets along with their elements
for (i = 0; i < NBUCKET; i++) {
printf("Bucket[%d]: ", i);
printBuckets(buckets[i]);
printf("\n");
}
// Sort the elements of each bucket
for (i = 0; i < NBUCKET; ++i) {
buckets[i] = InsertionSort(buckets[i]);
}
printf("-------------\n");
printf("Buckets after sorting\n");
for (i = 0; i < NBUCKET; i++) {
printf("Bucket[%d]: ", i);
printBuckets(buckets[i]);
printf("\n");
}

22
// Put sorted elements on arr
for (j = 0, i = 0; i < NBUCKET; ++i) {
struct Node *node;
node = buckets[i];
while (node) {
arr[j++] = node->data;
node = node->next;
}
}
return;
}
// Function to sort the elements of each bucket
struct Node *InsertionSort(struct Node *list) {
struct Node *k, *nodeList;
if (list == 0 || list->next == 0) {
return list;
}
nodeList = list;
k = list->next;
nodeList->next = 0;
while (k != 0) {
struct Node *ptr;
if (nodeList->data > k->data) {
struct Node *tmp;
tmp = k;
k = k->next;
tmp->next = nodeList;
nodeList = tmp;
continue;
}
for (ptr = nodeList; ptr->next != 0; ptr = ptr->next) {
if (ptr->next->data > k->data)
break;
}
if (ptr->next != 0) {
struct Node *tmp;
tmp = k;
k = k->next;
tmp->next = ptr->next;

23
ptr->next = tmp;
continue;
} else {
ptr->next = k;
k = k->next;
ptr->next->next = 0;
continue;
}
}
return nodeList;
}
int getBucketIndex(int value) {
return value / INTERVAL;
}
void print(int ar[]) {
int i;
for (i = 0; i < NARRAY; ++i) {
printf("%d ", ar[i]);
}
printf("\n");
}
// Print buckets
void printBuckets(struct Node *list) {
struct Node *cur = list;
while (cur) {
printf("%d ", cur->data);
cur = cur->next;
}
}
// Driver code
int main(void) {
int array[NARRAY] = {42, 32, 33, 52, 37, 47, 51};
printf("Initial array: ");
print(array);
printf("-------------\n");
BucketSort(array);
printf("-------------\n");
printf("Sorted array: ");
print(array);

24
return 0;
}

25
Program- 9

Aim - WAP to sort an array using Counting sort.

Algorithm:
Consider an array Arr[] of size N that we want to sort:

1.  Declare an auxiliary array Aux[] of size max(Arr[])+1 and initialize


it with 0.
2.  Traverse array Arr[] and map each element of Arr[] as an index
of Aux[] array, i.e., execute Aux[Arr[i]]++ for 0 <= i < N.  

3. Calculate the prefix sum at every index of array Arr[]. 


4.  Create an array sortedArr[] of size N.

5. Traverse array Arr[] from right to left and update sortedArr[] as


sortedArr[ Aux[ Arr[i] ] - 1] - Arr[i]. Also, update Aux[] as 
Aux[ Arr[i]]--.

Counting sort Implementation in C:

#include<stdio.h>
#include<limits.h>
#include<stdlib.h>
void printArray(int *A, int n)
{
for (int i = 0; i < n; i++)
{
printf("%d ", A[i]);
}
printf("\n");
}
int maximum(int A[], int n){
int max = INT_MIN;

26
for (int i = 0; i < n; i++)
{
if (max < A[i]){
max = A[i];
}
}
return max;
}
void countSort(int * A, int n){
int i, j;
// Find the maximum element in A
int max = maximum(A, n);
// Create the count array
int* count = (int *) malloc((max+1)*sizeof(int));
// Initialize the array elements to 0
for (i = 0; i < max+1; i++)
{
count[i] = 0;
}
// Increment the corresponding index in the count array
for (i = 0; i < n; i++)
{
count[A[i]] = count[A[i]] + 1;
}
i =0; // counter for count array
j =0; // counter for given array A
while(i<= max){
if(count[i]>0){
A[j] = i;
count[i] = count[i] - 1;
j++;
}
else{
i++;
}
}
}

int main(){

27
int A[] = {9, 1, 4, 14, 4, 15, 6};
int n = 7;
printf("Unsorted array:\n");
printArray(A, n);
countSort(A, n);
printf("Sorted array:\n");
printArray(A, n);
return 0;
}

28
Program- 10

Aim - Implementation of tree traversal.

Algorithm:
Inorder traversal
1. First,visit all nodes in the left subtree.
2. Then, the root node.
3. Visit all the nodes in the right subtree.

Preorder traversal

1. Visit the root node.


2. Visit all the nodes in the left subtree.
3. Visit all the nodes in the right subtree.

Postorder traversal

1. Visit all the nodes in the left subtree.


2. Visit all the nodes in the right subtree.
3. Visit the root node.

29
Implementation of tree traversal in C:

#include <stdio.h>
#include <stdlib.h>
struct node {
int item;
struct node* left;
struct node* right;
};

// Inorder traversal
void inorderTraversal(struct node* root) {
if (root == NULL) return;
inorderTraversal(root->left);
printf("%d ->", root->item);
inorderTraversal(root->right);
}
// preorderTraversal traversal

void preorderTraversal(struct node* root) {

if (root == NULL) return;


printf("%d ->", root->item);
preorderTraversal(root->left);
preorderTraversal(root->right);
}

// postorderTraversal traversal

void postorderTraversal(struct node* root) {


if (root == NULL) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ->", root->item);
}

// Create a new Node


struct node* createNode(value) {

30
struct node* newNode = malloc(sizeof(struct node));
newNode->item = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Insert on the left of the node
struct node* insertLeft(struct node* root, int value) {
root->left = createNode(value);
return root->left;
}
// Insert on the right of the node
struct node* insertRight(struct node* root, int value) {

root->right = createNode(value);
return root->right;
}
int main() {
struct node* root = createNode(1);
insertLeft(root, 12);
insertRight(root, 9);
insertLeft(root->left, 5);
insertRight(root->left, 6);
printf("Inorder traversal \n");
inorderTraversal(root);

printf("\nPreorder traversal \n");


preorderTraversal(root);
printf("\Postorder traversal \n");
postorderTraversal(root);
}

31
32
33
34

You might also like