Lab Manual - DSA
Lab Manual - DSA
Code:
#include <iostream>
using namespace std;
int linearSearch(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Return the index of the target element
}
}
return -1; // Element not found
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
int target;
if (result != -1) {
cout << "Element found at index " << result << endl;
} else {
cout << "Element not found." << endl;
}
return 0;
}
Binary Search:
Binary search is an efficient algorithm that works on sorted arrays. It divides the search interval
in half and repeatedly compares the middle element with the target value until the value is found
or the interval is empty.
• Time Complexity: O (log n)
• Space Complexity: O (1) for iterative implementation and O (log n) for recursive
implementation.
• Best Case: O (1) (When the middle element is the target)
• Average Case: O (log n)
• Worst Case: O (log n) (When the search interval reduces to a single element)
Task-2
Write a C++ Program for Binary Search
Algorithm:
1. Start with two pointers, low and high, representing the bounds of the search interval.
2. Calculate the middle index: mid = low + (high - low) / 2.
3. If the middle element matches the target, return the index.
4. If the target is less than the middle element, adjust high = mid - 1.
5. If the target is greater, adjust low = mid + 1.
6. Repeat steps 2-5 until low > high or the element is found.
Code:
#include <iostream>
using namespace std;
if (arr[mid] == target) {
return mid; // Return the index of the target element
}
if (arr[mid] < target) {
low = mid + 1; // Search in the right half
} else {
high = mid - 1; // Search in the left half
}
}
return -1; // Element not found
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
int target;
if (result != -1) {
cout << "Element found at index " << result << endl;
} else {
cout << "Element not found." << endl;
}
return 0;
}
Procedure:
1. Write the code for linear and binary search as given above.
2. Compile the program using a C++ compiler.
3. Run the program and input the target element to search.
4. Observe the outputs and verify the correctness of the algorithms.
5. Analyze the time taken for each algorithm by testing with different input sizes.
Observations:
• Note down the time taken by each search method for various input sizes.
• Compare the performance of linear search and binary search.
Conclusion:
• Linear search is simple but inefficient for large datasets.
• Binary search is highly efficient but requires the dataset to be sorted.
Questions:
1. What is the difference between linear search and binary search?
2. Why does binary search require the array to be sorted?
3. What is the time complexity of binary search?
4. Can binary search be implemented on linked lists? Why or why not?
5. How can you modify binary search for descending order arrays?