Desing and Analysis of Alogorithm
Desing and Analysis of Alogorithm
Desing and Analysis of Alogorithm
AND TECHNOLOGY
FARAH, MATHURA
KCS-553
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.
2
Program-1
Algorithm:
1. Set min to the first location.
3. Swap the first location with the minimum value in the array.
4. Assign the second element as min.
#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++)
{
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
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.
#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;
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
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-
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>
int main()
{
int n,i;
int arr[n];
quickSort(arr,0,n-1);
for(i=0;i<n;i++)
printf("%d ",arr[i]);
printf("\n");
return 0;
}
8
int pIndex = partition(arr, start, end);
quickSort(arr, start, pIndex-1);
quickSort(arr, pIndex+1, end);
}
}
9
Program-4
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.
#include <stdio.h>
10
if (array[i] > array[i + 1]) {
// 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};
11
Program-5
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)
#include <stdio.h>
void printArray(int *A, int n)
{
for (int i = 0; i < n; i++)
{
printf("%d ", A[i]);
}
printf("\n");
}
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];
}
}
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
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.
#include <stdio.h>
15
largest = left;
// Heap sort
for (int i = n - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);
// 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};
17
Program- 7
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
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!
#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);
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
Algorithm:
Consider an array Arr[] of size N that we want to sort:
#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
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
Postorder traversal
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
// postorderTraversal traversal
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);
31
32
33
34