2.3.1 Searching Algorithms Flashcards
Which search algorithm requires data to be sorted before perfoming the algorithm?
Binary Search
Perform linear search for 9 :
[ 1, 2, 3, 5, 7, 9, 11, 12 ]
Check till find 9 and then terminates.
What is the time complexity of Binary Search?
O (log n)
Very efficient for more items
Perform Binary search for 6 :
[ 1, 3, 6, 7, 9, 12, 13 ]
- Goes to midpoint, 7
- 6 < 7 Therefore goes to the left of 7
- Array is now [ 1, 3, 6 ]
- Goes to midpoint, 3
- 6 > 3 Therefore goes to the right of 3
- Array is now [ 6 ]
- 6 = 6 Therefore 6 is found and Algorithm terminates
Which search algorithm has a time complexity of O(n)?
Linear Search
Which sorting algorithm is the most time efficient ; Bubble or Merge
Merge Sort
Merge is O (n log n) Bubble has a best case O(1) and a worst of O(n^2)
Which sorting algorithm uses divide and conquer?
Merge Sort
Time Complexity of Bubble Sort?
O(1) - Best case
O(n^2) - Worst case
Time complexity of Merge Sort?
O ( n log n)
Sort into ascending using bubble sort :
4 3 5 7 6
- [ 4 3 5 7 6 ]
- [(3 4) 5 7 6]
- [3 4 5 (6 7)]
- [ 3 4 5 6 7 ]
brackets show the switches remember that it will go through fully after
Sort in alphabetical order using merge sort:
Tom Sue Jack Bill Ada
- Separate into 3 and 2
- Tom Sue Jack → Jack Sue Tom
- Bill Ada → Ada Bill
- Combine to get Ada Bill Jack Sue Tom