Lec 2
Lec 2
Introduction to Searching
•What is a Search Algorithm ?
A method for finding a target value within a data structure (e.g., array, list).
•Comm on Types:
data sequentially to look for the desired data. The data need not be in a sorted manner for this type
of search
❑Checks every element in a collection sequentially until the target is found or the list ends.
Linear (Sequential ) Search
❑Algorithm Steps:
• Key Idea:
• Adjacent elements are compared and swapped if they are in the wrong order, “bubbling” the
largest element to the top on each pass.
Bubble Sort
Bubble Sort
1. Start at the beginning of the array.
2. Compare adjacent elements:
• If the element on the left is greater than the one on the right, swap them.
3. Continue through the array:
• Perform comparisons for every pair in the current pass.
4. Repeat the process:
• After each pass, the largest unsorted element moves to its correct position at the end.
5. Terminate:
• When a pass is completed without any swaps, the array is sorted.
Bubble Sort
❑Time Complexity:
• Worst-case: O(n²)
❑Advantages:
❑Disadvantages:
• Basic Idea:
• It works similarly to how you might sort playing cards in your hand.
INSERTION SORT
❑ How Insertion Sort Works
1. Start with the first element:
• Consider it as the sorted portion.
2. Take the next element (key):
• Compare it with elements in the sorted portion.
3. Shift elements:
• Move elements that are larger than the key to the right.
4. Insert the key:
• Place the key in its correct position.
5. Repeat:
• Continue until the entire array is sorted.
INSERTION SORT
INSERTION SORT
❑ Time Complexity:
❑ Worst-case: O(n²) (e.g., reverse-sorted array)
❑ Best-case: O(n) (e.g., already sorted array)
INSERTION SORT
❑ Advantages:
➢ Simple to implement and understand
➢ Efficient for small or nearly sorted arrays
➢ Adaptive: Performs well if the array is partially sorted
❑ Disadvantages:
▪ Inefficient for large datasets due to quadratic time complexity in the worst-case
▪ High number of shifts compared to more advanced algorithms