Daa Lab PDF
Daa Lab PDF
APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)
Lab File
Design and Analysis of Algorithm Lab (BCS-553)
Session: 2024-25
Submitted By:
Submitted To: Name: Jayant Kumar
Mr. Amit Kumar Himanshu Roll No.: 2201921530209
Branch: CSEAIML
Sec: CSAIML-4
Semester: V
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)
INDEX
Date of Date of
S. No. List of Programs Signature
Experiment Submission
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)
Program No -1
Aim: - Write a program to implement the Insertion Sort using array.
Insertion Sort:-
• Insertion sort is a simple sorting algorithm that works similar to the way you sort
playing cards in your hands. The array is virtually split into a sorted and an unsorted
part. Values from the unsorted part are picked and placed at the correct position in the
sorted part.
• Insertion Sort is a simple sorting algorithm that builds the final sorted array one item at
a time. It works by considering one element at a time and comparing it with the elements
to its left, shifting elements to the right as necessary to make room for the current
element.
Complexity:-
• Worst case complexity: O(n2)
• Best-case complexity: O(n)
• Average-case complexity: O(n2)
Algorithm:-
for j = 2 to A.length
key = A[j]
// Insert A[j] into the sorted sequence A[1.. j - 1]
i=j-1
while i > 0 and A[i] > key
A[i + 1] = A[i]
i = i -1
A[i + 1] = key
Process:
• With each iteration one element from the second part is picked and inserted into the
first part of array at its correct position by shifting the existing elements if required.
• This goes until the last element in second part of array is placed in correct position in
the output array.
• Now, we have the array in sorted order.
Source Code:-
#include<stdio.h>
int main() {
int n, temp, a[30];
printf("Enter the size of array\n");
scanf("%d",&n);
printf("Enter %d elements: \n",n);
for(int i=0; i<n; i++){
scanf("%d",&a[i]);
}
for(int i = 1; i <= n - 1; i++) {
for(int j = i; j > 0 && a[j - 1] > a[j]; j--) {
int temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
} printf("Sorted Array : ");
for(int i=0;i<n;i++){
printf("%d ",a[i]);
}
return 0;
}
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)
Output:-
Enter the size of array
5
Enter 5 elements:
12 5 8 19 3
Sorted Array :
3 5 8 12 19
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)
Program No -2
• Selection sort is a simple sorting algorithm. This sorting algorithm, like insertion sort, is
an in-place comparison-based algorithm in which the list is divided into two parts, the
sorted part at the left end and the unsorted part at the right end. Initially, the sorted part
is empty and the unsorted part is the entire list.
• The smallest element is selected from the unsorted array and swapped with the leftmost
element, and that element becomes a part of the sorted array. This process continues
moving unsorted array boundaries by one element to the right.
Complexity:-
Algorithm:-
For i← 1 to n-1
do min j ←i;
min x ← A[i]
for j ←i + 1 to n
then
min j ← j
min x ← A[j]
A[min j] ← A [i]
A[i] ← min x
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)
Process:
Source Code:-
#include<stdio.h>
int main() {
int n, i, j, temp, a[30], min;
printf("Enter the size of array : \n");
scanf("%d",&n);
printf("Enter %d elements : \n",n);
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
} for (i = 0; i < n-1; i++) {
min = i;
for (j = i+1; j < n; j++) {
if (a[j] < a[min]) {
min = j;
}
} temp = a[min];
a[min] = a[i];
a[i] = temp;
} printf("Sorted Array : ");
for(int i=0;i<n;i++){
printf("%d ",a[i]);
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)
}
return 0;
}
Output:-
Program No -3
Source Code:-
#include <stdio.h>
int main() {
int array[100], n, i, j, swap;
printf("Enter the size of array\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
scanf("%d", &array[i]);
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
swap = array[j];
array[j] = array[j + 1];
array[j + 1] = swap;
}
}
}
printf("Sorted array: ");
for (i = 0; i < n; i++)
printf("%d ", array[i]);
printf("\n");
return 0;
}
Output:-
Program No -4
Aim: - Write a program to implement the Binary Search using array.
Binary Search: -
• Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly
dividing the search interval in half.
• It is a search algorithm used to find the position of a target value within a sorted array.
It works by repeatedly dividing the search interval in half until the target value is
found or the interval is empty. The search interval is halved by comparing the target
element with the middle value of the search space.
Complexity:-
Algorithm:-
• Divide the search space into two halves by finding the middle index mid.
• Compare the middle element of the search space with the key.
• If the key is found at middle element, the process is terminated.
• If the key is not found at middle element, choose which half will be used as the next
search space.
• If the key is smaller than the middle element, then the left side is used for next search.
• If the key is larger than the middle element, then the right side is used for next search.
• This process is continued until the key is found or the total search space is exhausted.
Process:
• Start with two pointers, low at the beginning and high at the end of the array.
• Calculate the middle index: mid = (low + high) / 2.
Compare the target value with the middle element of the array.
• If the target value equals the middle element, the search is successful, and the index is
returned.
• If the target value is less than the middle element, adjust the high pointer to mid - 1 to
search the left half.
• If the target value is greater than the middle element, adjust the low pointer to mid + 1
to search the right half.
• Continue the process until the low pointer exceeds the high pointer or the target value
is found.
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)
#include <stdio.h>
int main() {
int n, i, x, beg, end, mid, flag=0;
int a[100];
printf("Enter the size of array: ");
scanf("%d", &n);
printf("Enter the array elements in sorted order:\n");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
} printf("Enter the element to be searched: ");
scanf("%d", &x);
beg = 0;
end = n - 1;
while (beg <= end) {
mid = (beg + end) / 2;
if (a[mid] == x) {
printf("Element %d is found at index value %d\n", x, mid);
flag = 1;
break;
}
if (a[mid] > x) {
end = mid - 1;
} else {
beg = mid + 1;
}
} if (!flag) {
printf("No such element is found\n");
} return 0;
}
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)
#include <stdio.h>
int binarySearch(int a[], int beg, int end, int x) {
if (beg > end) {
return -1;
} int mid = beg + (end - beg) / 2;
if (a[mid] == x) {
return mid;
} else if (a[mid] > x) {
return binarySearch(a, beg, mid - 1, x);
} else {
return binarySearch(a, mid + 1, end, x);
}
} int main() {
int n, i, x, result;
int a[100];
printf("Enter the size of array: ");
scanf("%d", &n);
printf("Enter the array elements in sorted order:\n");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
printf("Enter the element to be searched: ");
scanf("%d", &x);
result = binarySearch(a, 0, n - 1, x);
if (result != -1) {
printf("Element %d is found at index value %d\n", x, result);
} else {
printf("No such element is found\n");
} return 0;
}
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)
Output:-
Program No -5
Process:
- Recursively divide the array until each subarray contains only one element.
- Merge the divided subarrays in a sorted manner.
- Continue merging until the entire array is sorted.
Source Code:
#include <stdio.h>
i = 0;
j = 0;
k = left;
int main() {
int array[100], n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++)
scanf("%d", &array[i]);
mergeSort(array, 0, n - 1);
printf("\n");
return 0;
}
Output:
Program No -6
Heap Sort:
- Heap Sort is a comparison-based sorting algorithm that uses a binary heap data structure.
The algorithm builds a heap from the input data, then repeatedly extracts the maximum
element and rebuilds the heap until all elements are sorted.
- Heap: A complete binary tree where the value of each node is greater than or equal to the
values of its children (Max-Heap).
Complexity:
- Worst-case complexity: O(n log n)
- Best-case complexity: O(n log n)
- Average-case complexity: O(n log n)
Algorithm:
- Heapify: Build a max heap from the input data.
- Extract: Swap the root (maximum value) with the last element and reduce the heap size.
- Rebuild: Recursively heapify the root to maintain the heap property.
- Repeat: Continue until the heap size is reduced to 1.
Process:
- Build a max heap from the unsorted array.
- Swap the maximum element (root) with the last element in the array.
- Reduce the size of the heap and recursively heapify the remaining elements.
- Repeat the process until the entire array is sorted.
Source Code:
#include <stdio.h>
largest = left;
if (largest != i) {
int temp = array[i];
array[i] = array[largest];
array[largest] = temp;
heapify(array, n, largest);
}
}
heapify(array, i, 0);
}
}
int main() {
int array[100], n, i;
heapSort(array, n);
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)
printf("\n");
return 0;
}
Output:
Program No -7
Aim:- Write a program to count the number of Inversions in an array using the Merge
algorithm.
Inversion:
• The merge algorithm is a key component of the merge sort technique, which
efficiently sorts arrays.
• An inversion is a condition in which a pair of elements is out of order. Specifically,
for an array AAA, a pair (i,j)(i, j)(i,j) forms an inversion if i<ji < ji<j and
A[i]>A[j]A[i] > A[j]A[i]>A[j].
• By counting inversions during the merging of two sorted subarrays, we can determine
how out of order the array is.
Complexity:
- Worst-case complexity: O(n log n)
- Best-case complexity: O(n log n)
- Average-case complexity: O(n log n)
Algorithm:
- Start by dividing the array into two sorted subarrays.
- Merge the two sorted subarrays while counting the inversions:
• Compare elements of both subarrays.
• If an element in the left subarray is greater than an element in the right subarray, count
how many elements are left in the left subarray (as they are all inversions).
- Continue until all elements are merged and counted.
Process:
- Take two sorted subarrays.
- Use the merge function to combine them and count the inversions.
- Display the total count of inversions and the final merged array..
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)
Source Code:
#include <stdio.h>
int countInversions(int left[], int right[], int n1, int n2, int merged[]) {
int i = 0, j = 0, k = 0;
int inversion_count = 0;
while (i < n1 && j < n2) {
if (left[i] <= right[j]) {
merged[k++] = left[i++];
} else {
merged[k++] = right[j++];
inversion_count += (n1 - i);
}
}
while (i < n1)
merged[k++] = left[i++];
while (j < n2)
merged[k++] = right[j++];
return inversion_count;
}
int main() {
int left[] = {10, 50, 60, 70};
int right[] = {15, 20, 30, 80};
int n1 = sizeof(left) / sizeof(left[0]);
int n2 = sizeof(right) / sizeof(right[0]);
int merged[n1 + n2];
int inversion_count = countInversions(left, right, n1, n2, merged);
printf("Number of inversions: %d\n", inversion_count);
printf("Merged array: ");
for (int i = 0; i < n1 + n2; i++) {
printf("%d ", merged[i]);
}
printf("\n");
return 0;
}
Output:
Number of inversions: 6
Merged array: 10 15 20 30 50 60 70 80
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)
Program No -8
Complexity:
- Worst-case complexity: O(n²)
- Best-case complexity: O(n log n)
- Average-case complexity: O(n log n)
Algorithm:
- Start: Select a pivot element from the array.
- Partition: Rearrange elements so that all elements less than the pivot come before it, and all
elements greater come after it.
- Recursion: Recursively apply the same process to the sub-arrays formed by partitioning.
- End: Repeat until the array is fully sorted.
Process:
1. Select a pivot element (usually the last element).
2. Rearrange elements around the pivot such that elements smaller than the pivot are to the
left and larger elements to the right.
3. Recursively apply the steps to the left and right partitions until the base case (sub-arrays of
size 1 or 0) is reached.
Source Code:
#include <stdio.h>
int main() {
int data[] = {8, 7, 6, 1, 0, 9, 2};
int n = sizeof(data) / sizeof(data[0]);
quickSort(data, 0, n - 1);
Output:
Sorted array:
0126789
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)
Program No -9
Shell Sort:
- Shell Sort is a generalization of insertion sort that allows the exchange of far-apart elements
to speed up the sorting process. It works by repeatedly sorting elements that are a certain
distance apart (gap), gradually reducing the gap.
Complexity:
- Worst-case complexity: O(n²)
- Best-case complexity: O(n log n)
- Average-case complexity: O(n log² n)
Algorithm:
- Start: Divide the list into smaller sub-lists.
- Gap: Select a gap value and sort sub-lists formed by the gap.
- Insertion Sort: Apply the insertion sort algorithm to the sub-lists.
- Repeat: Reduce the gap size and repeat the process.
- End: The process ends when the gap is reduced to 1, effectively performing an insertion
sort.
Process:
1. Choose an initial gap (typically n/2).
2. Apply insertion sort for elements at that gap distance.
3. Reduce the gap and repeat until the gap becomes 1.
Source Code:
#include <stdio.h>
void shellSort(int arr[], int n) {
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i++) {
int temp = arr[i];
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
arr[j] = arr[j - gap];
arr[j] = temp;
}}}
int main() {
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)
Output:
Sorted array: 2 3 12 34 54
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)
Program No -10
Complexity:
- Worst-case complexity: O(n + k)
- Best-case complexity: O(n + k)
- Average-case complexity: O(n + k)
Algorithm:
- Start: Count the occurrences of each element.
- Accumulate: Modify the count array to accumulate the counts.
- Place: Place each element in its correct sorted position based on the counts.
- End: Output the sorted array.
Process:
1. Count the occurrences of each element.
2. Update the count array by adding the previous counts.
3. Place the elements in their correct positions.
Source Code:
#include <stdio.h>
int main() {
int array[] = {4, 2, 2, 8, 3, 3, 1};
int size = sizeof(array) / sizeof(array[0]);
countingSort(array, size);
Output:
Sorted array: 1 2 2 3 3 4 8
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)
Program No -11
Radix Sort:
- Radix Sort sorts elements by processing individual digits of each number, starting from the
least significant bit (LSB) to the most significant bit (MSB).
Complexity:
- Worst-case complexity: O(nk) (where k is the number of digits in the largest number)
- Best-case complexity: O(nk)
- Average-case complexity: O(nk)
Algorithm:
- Start: Group the numbers by their least significant digit.
- Sort: Sort each group, and repeat the process for each more significant digit.
- Repeat: Continue until all digits have been processed.
- End: The array is sorted.
Process:
1. Perform a stable sort for each digit.
2. Process from the least significant to the most significant digit.
Source Code:
#include <stdio.h>
int output[n];
int count[10] = {0};
for (int i = 0; i < n; i++)
count[(arr[i] / exp) % 10]++;
arr[i] = output[i];
}
int main() {
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr) / sizeof(arr[0]);
radixSort(arr, n);
printf("Sorted array: \n");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
Output:
Program No -12
Aim: Write a program to implement Bucket Sort using an array.
Bucket Sort:
- Bucket Sort divides elements into buckets, sorts each bucket individually, and then merges
the buckets to get the sorted array.
Complexity:
- Worst-case complexity: O(n²)
- Best-case complexity: O(n + k)
- Average-case complexity: O(n + k)
Algorithm:
- Start: Divide the array into buckets.
- Sort: Sort each bucket using another sorting algorithm (usually Insertion Sort).
- Merge: Merge the sorted buckets into a single sorted array.
- End: The array is sorted.
Process:
1. Create buckets and distribute the elements.
2. Sort each bucket.
3. Combine the sorted buckets into the final sorted array.
Source Code:
#include <stdio.h>
#include <stdlib.h>
#define NBUCKET 10
#define INTERVAL 10
struct Node {
int data;
struct Node *next;
};
int main() {
int array[] = {29, 25, 3, 49, 9, 37, 21, 43};
int n = sizeof(array) / sizeof(array[0]);
bucketSort(array, n);
Output:
Sorted array: 3 9 21 25 29 37 43 49