0% found this document useful (0 votes)
15 views15 pages

KCS553 - DAA Lab

The document discusses the design and analysis of algorithms, focusing on efficient problem-solving methods in computer science. It covers linear and binary search algorithms, their time complexities, and provides source code examples for recursive implementations. Additionally, it introduces insertion sort and quick sort, detailing their algorithms, time complexities, and practical applications.

Uploaded by

priyansh Chhabra
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)
15 views15 pages

KCS553 - DAA Lab

The document discusses the design and analysis of algorithms, focusing on efficient problem-solving methods in computer science. It covers linear and binary search algorithms, their time complexities, and provides source code examples for recursive implementations. Additionally, it introduces insertion sort and quick sort, detailing their algorithms, time complexities, and practical applications.

Uploaded by

priyansh Chhabra
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
You are on page 1/ 15

INTRODUCTION

The “Design and Analysis Of Algorithm” is a field of computer science that focuses on the study of
algorithms which are step-by-step procedure or sets of instructions for solving specific
problems or tasks in a finite number of steps.

Algorithm Design involves the process of creating efficient algorithms to solve particular problems.
It's about coming up with a well-structured and logically sound sequence of steps to perform a
task. Good algorithm design aims to optimise factors like time complexity (how quickly an
algorithm runs) and space complexity (how much memory an algorithm uses).
There are various strategies for algorithm design, including divide and conquer, dynamic
programming, greedy algorithms, and more.

Algorithm Analysis once an algorithm is designed, it needs to be analysed to understand its


performance characteristics. This analysis involves evaluating how an algorithm's efficiency
scales with input size. Key aspects of algorithm analysis include worst-case, best-case, and
average-case time and space complexity. The goal is to determine how well an algorithm
performs under various conditions and to compare different algorithms to choose the most
suitable one for a particular problem.

The importance of design and analysis of algorithms lies in optimising computational processes.
Efficient algorithms can significantly reduce the time and resources required to solve
problems, which is crucial in computer science, where efficiency is often a critical factor.

The field of algorithm design and analysis is fundamental in computer science and has broad
applications across various domains as:

➢ Problem Solving
➢ Artificial Intelligence
➢ Data Science
➢ Cryptography
➢ Network routing and many others.

1
1 2100971520035
PROGRAM - 1

OBJECTIVE : Write a Program for recursive linear search and recursive binary search.

DESCRIPTION :

1. LINEAR SEARCH

A linear search program is a simple algorithmic program that searches for a specific element in
an array or list by sequentially examining each element one by one. It starts from the
beginning and compares each element with the target value until a match is found or the
entire array is searched. Linear search is straightforward but less efficient for large
datasets, as it may require scanning through all elements in the worst case. It is easy to
implement and suitable for unsorted or small datasets where efficiency is not a critical
concern. Linear search is a fundamental algorithm used in various applications,
including searching and data retrieval tasks.

2. BINARY SEARCH

A binary search program is an efficient algorithm used to find a specific target element within a
sorted array or list. It works by repeatedly dividing the search range in half, eliminating
half of the remaining elements in each iteration. This process continues until the target
element is found or determined to be absent. Binary search is significantly faster than
linear search for large datasets because it reduces the search space exponentially with
each comparison. It has a time complexity of O(log n), making it suitable for searching
in large datasets or databases.

TIME COMPLEXITY :

Time complexity is a measure of the computational resources required for an algorithm to


solve a problem, and it is often expressed in terms of the size of the input data (n). Let's
discuss the time complexity of linear search and binary search:

1. LINEAR SEARCH :

Time Complexity : O(n)


Description : In a linear search, you sequentially examine each element in the data structure (e.g., an
array or list) until you find the target element or determine that it doesn't exist. This means you may
need to check every element in the worst case, resulting in a linear time complexity.
Use Cases : Linear search is suitable for small datasets or unsorted data where you don't have any
information about the order of elements.

2
2 2100971520035
2. BINARY SEARCH :

Time Complexity : O(log n)


Description : Binary search operates on sorted data. It repeatedly divides the search
range in half and compares the target element with the middle element. Depending on the comparison,
it either continues the search in the left or right half. This process eliminates half of the remaining
elements with each comparison, leading to a time complexity of O(log n).
Use Cases : Binary search is highly efficient for searching in large sorted datasets, such as in databases
or when working with sorted arrays. It's especially valuable when you need to find elements quickly,
as it reduces the search space exponentially.

In summary, the key difference in time complexity between linear search and binary search is their
growth rate concerning the input size (n). Linear search has a linear time complexity (O(n)), making it
suitable for small datasets or unsorted data. Binary search, on the other hand, has a logarithmic time
complexity (O(log n)), which makes it significantly faster for large sorted datasets where you need to
quickly locate specific elements.

ALGORITHM :

1. RECURSIVE LINEAR SEARCH ALGORITHM :

RecursiveLinearSearch( arr, target, index, size):


if index >= size:
return -1 // Element not found

if arr[index] == target:
return index // Element found at this index

return RecursiveLinearSearch(arr, target, index + 1, size) // Recursively search the next index

2. RECURSIVE BINARY SEARCH ALGORITHM :

RecursiveBinarySearch(arr, target, left, right):


if left > right:
return -1 // Element not found

mid = left + (right - left) / 2

if arr[mid] == target:
return mid // Element found at mid

if arr[mid] < target:


return RecursiveBinarySearch(arr, target, mid + 1, right) // Search in the right half

return RecursiveBinarySearch(arr, target, left, mid - 1) // Search in the left half

3
3 2100971520035
SOURCE CODE :

1. RECURSIVE LINEAR SEARCH :

LAB/LinearSearch.c

1 #include <stdio.h> // PRIYANSH CHHABRA , CSE-AI , 2100971520035


2
3 int recursiveLinearSearch(int arr[], int size, int target, int index)
4 {
5 if (index >= size) {
6 return -1;
7 }
8
9 if (arr[index] == target) {
10 return index;
11 }
12
13 return recursiveLinearSearch(arr, size, target, index + 1);
14 }
15
16 int main()
17 {
18 int size, target;
19
20 printf("THIS CODE IS WRITTEN BY PRIYANSH CHHABRA\n");
21
22 printf("\nEnter the number of elements in the array: ");
23 scanf("%d", &size);
24
25 int arr[size];
26
27 printf("Enter the elements of the array:\n");
28 for (int i = 0; i < size; i++) {
29 scanf("%d", &arr[i]);
30 }
31
32 printf("\nEnter the target value to search: ");
33 scanf("%d", &target);
34
35 int index = recursiveLinearSearch(arr, size, target, 0);
36
37 if (index != -1)
38 {
39 printf("\nElement found at index %d.\n", index);
40 }
41 else
42 {
43 printf("\nElement not found in the array.\n");
44 }
45
46 return 0;
47 }

4
4 2100971520035
OUTPUT :

5
5 2100971520035
2. RECURSIVE BINARY SEARCH :

LAB/BinarySearch.c

1 #include <stdio.h> // PRIYANSH CHHABRA , CSE-AI , 2100971520035


2
3 int recursiveBinarySearch(int arr[], int left, int right, int target) {
4 if (left > right)
5 {
6 return -1;
7 }
8 int mid = left + (right - left) / 2;
9
10 if (arr[mid] == target)
11 {
12 return mid;
13 }
14 else if (arr[mid] < target)
15 {
16 return recursiveBinarySearch(arr, mid + 1, right, target);
17 }
18 else
19 {
20 return recursiveBinarySearch(arr, left, mid - 1, target);
21 }
22 }
23 int main()
24 {
25 int size, target;
26
27 printf("\nTHIS CODE IS WRITTEN BY PRIYANSH CHHABRA\n");
28
29 printf("\nEnter the number of elements in the sorted array: ");
30 scanf("%d", &size);
31
32 int arr[size];
33
34 printf("\nEnter the sorted elements of the array:\n");
35 for (int i = 0; i < size; i++)
36 {
37 scanf("%d", &arr[i]);
38 }
39
40 printf("\nEnter the target value to search: ");
41 scanf("%d", &target);
42
43 int index = recursiveBinarySearch(arr, 0, size - 1, target);
44 if (index != -1)
45 {
46 printf("\nElement found at index %d.\n", index);
47 }
48 else
49 {
50 printf("\nElement not found in the array.\n");
51 }
52 return 0;
53 }

6
6 2100971520035
OUTPUT :

7
7 2100971520035
PROGRAM - 2

OBJECTIVE : Write a Program for Insertion Sort.

DESCRIPTION :

INSERTION SORT :

The insertion sort program in C is a simple sorting algorithm that organises an array of elements
in ascending order. It iterates through the array, considering one element at a time and
placing it in its correct position among the previously sorted elements. This process
continues until the entire array is sorted. Users input the number of elements and the
array values, and the program efficiently sorts the array using the insertion sort
technique. The sorted array is then displayed, making it a practical tool for arranging
data in a straightforward manner.

TIME COMPLEXITY :

INSERTION SORT :

Insertion sort is a straightforward sorting algorithm that works well for small datasets or partially
sorted data but is less efficient for large datasets. Its time complexity can be analysed as
follows:

1. Best-case Time Complexity: When the input array is already sorted in ascending order,
insertion sort has a best-case time complexity of O(n). This is because it only needs to
make one pass through the array to confirm that each element is in its correct position.

2. Average-case Time Complexity: In the average case, insertion sort has a time complexity of
O(n^2), where n is the number of elements in the array. This is because, on average, it
needs to make roughly n/2 comparisons and swaps for each element.

3. Worst-case Time Complexity: In the worst-case scenario, when the input array is sorted in
descending order, insertion sort has a time complexity of O(n^2). This occurs because,
for each element in the array, it needs to compare and move it to its correct position,
leading to a quadratic number of operations.

Insertion sort is considered an "in-place" sorting algorithm because it sorts the elements within
the original array without requiring additional memory allocation. However, its time
complexity makes it less efficient than more advanced sorting algorithms like quick sort
or merge sort for larger datasets.

While insertion sort is not the most efficient sorting algorithm for large datasets, it can still be
useful for small datasets or for situations where the data is already partially sorted, as its
best-case performance is quite good.

8
8 2100971520035
ALGORITHM :

Input: An array of n elements [arr[0], arr[1], ..., arr[n-1]]

Output: The array sorted in ascending order

1. Start with the second element (index 1) and consider it as the current element.
2. Compare the current element with the one before it (previous element).
3. If the current element is smaller than the previous element, swap them.
4. Repeat step 2 and 3 until the current element is in its correct sorted position among the previous
elements.
5. Move to the next unsorted element (increment index) and repeat steps 2-4.
6. Continue this process until you have processed all elements in the array.
7. The array is now sorted in ascending order.

Pseudocode:
for i from 1 to n-1:
current_element = arr[i]
j=i-1
while j >= 0 and arr[j] > current_element:
arr[j + 1] = arr[j]
j=j-1
arr[j + 1] = current_element

9
9 2100971520035
SOURCE CODE :

LAB/InsertionSort.c

1 #include<stdio.h> // PRIYANSH CHHABRA, 2100971520035 , CSE-AI


2
3 void insertionSort(int arr[], int n) {
4 int i, key, j;
5 for (i = 1; i < n; i++) {
6 key = arr[i];
7 j = i - 1;
8
9 while (j >= 0 && arr[j] > key) {
10 arr[j + 1] = arr[j];
11 j = j - 1;
12 }
13 arr[j + 1] = key;
14 }
15 }
16
17 int main()
18 {
19 printf("\nTHIS CODE IS WRITTEN BY PRIYANSH CHHABRA\n");
20 int n;
21
22 printf("\nEnter the number of elements in the array: ");
23 scanf("%d", &n);
24
25 int arr[n];
26
27 printf("\nEnter the elements of the array:\n");
28 for (int i = 0; i < n; i++)
29 {
30 scanf("%d", &arr[i]);
31 }
32
33 insertionSort(arr, n);
34
35 printf("\nSorted array: ");
36 for (int i = 0; i < n; i++)
37 {
38 printf("%d ", arr[i]);
39 }
40 printf("\n");
41
42 return 0;
43 }
44

10
10 2100971520035
OUTPUT :

11
11 2100971520035
PROGRAM - 3

OBJECTIVE : Write a Program for Quick Sort.

DESCRIPTION :

QUICK SORT :

A Quick Sort program is an efficient sorting algorithm implemented in various programming


languages. It works by selecting a pivot element and partitioning the array into two
subarrays - elements less than the pivot and elements greater than the pivot. This
process is recursively applied to the subarrays, effectively dividing and conquering the
sorting task. Quick Sort has an average time complexity of O(n log n), making it one of
the fastest sorting algorithms. However, it can have a worst-case time complexity of
O(n^2) if the pivot selection is not optimised, but this is rare in practice.

TIME COMPLEXITY :

QUICK SORT :

Quick Sort is a highly efficient and widely used sorting algorithm, known for its average-case
time complexity of O(n log n). However, its time complexity can vary depending on
various factors, including the choice of the pivot element and the input data.

1. Average-case Time Complexity (Best Case): Quick Sort's average-case time complexity is
O(n log n), which makes it one of the fastest sorting algorithms for most practical
scenarios. The algorithm efficiently divides the array into smaller subarrays and sorts
them, resulting in a balanced recursion tree.

2. Worst-case Time Complexity: In the worst-case scenario, Quick Sort can have a time
complexity of O(n^2). This occurs when the pivot element is consistently chosen
poorly, causing the algorithm to create unbalanced partitions. However, various
strategies, such as choosing a random pivot or using the "median of three" method, can
mitigate the likelihood of encountering the worst-case scenario. With these
optimisations, worst-case scenarios are rare in practice.

3. Best-case Time Complexity: The best-case time complexity of Quick Sort is also O(n log
n). This occurs when the pivot is consistently chosen such that it roughly divides the
array into two equal-sized subarrays. In such cases, Quick Sort exhibits its optimal
performance.

12
12 2100971520035
ALGORITHM :

QuickSort(arr[], low, high)


if low < high
// Partition the array and get the pivot index
pivotIndex = Partition(arr, low, high)

// Recursively sort the two subarrays


QuickSort(arr, low, pivotIndex - 1)
QuickSort(arr, pivotIndex + 1, high)

Partition(arr[], low, high)


// Choose a pivot element (e.g., the last element)
pivot = arr[high]

// Initialise the index of the smaller element


smallerIndex = low - 1

for i = low to high-1


// If the current element is smaller than or equal to the pivot
if arr[i] <= pivot
// Swap arr[i] and arr[smallerIndex+1]
Swap(arr[i], arr[smallerIndex+1])
smallerIndex = smallerIndex + 1

// Swap the pivot element (arr[high]) with the element at (smallerIndex+1)


Swap(arr[high], arr[smallerIndex+1])

// Return the index of the pivot element


return smallerIndex + 1

13
13 2100971520035
SOURCE CODE :

LAB/QuickSort.c

1 #include <stdio.h>// PRIYANSH CHHABRA ,CSE-AI, 2100971520035


2 void printArray(int *A, int n)
3 {
4 for (int i = 0; i < n; i++)
5 {
6 printf("%d ", A[i]);
7 }
8 printf("\n");
9 }
10 int partition(int A[], int low, int high)
11 {
12 int pivot = A[low];
13 int i = low + 1;
14 int j = high;
15 int temp;
16 do
17 {
18 while (A[i] <= pivot)
19 {
20 i++;
21 }
22
23 while (A[j] > pivot)
24 {
25 j--;
26 }
27
28 if (i < j)
29 {
30 temp = A[i];
31 A[i] = A[j];
32 A[j] = temp;
33 }
34 } while (i < j);
35
36 temp = A[low];
37 A[low] = A[j];
38 A[j] = temp;
39 return j;
40 }
41 void quickSort(int A[], int low, int high)
42 {
43 int partitionIndex;
44
45 if (low < high)
46 {
47 partitionIndex = partition(A, low, high);
48 quickSort(A, low, partitionIndex - 1);
49 quickSort(A, partitionIndex + 1, high);
50 }
51 }
52 int main()
53 {

14
14 2100971520035
OUTPUT :

15
15 2100971520035

You might also like