An algorithm is a finite set of instructions, used to solve a problem.
Searching algorithms
Iterative sequential search
Recursive sequential search
Binary search
Works in a sorted array.
Time complexities
Algorithms
Best
Average
Worst
Sequential search
O(1)
O(n)
O(n)
Binary search
O(1)
O(log n)
O(log n)
Sorting algorithms
A sorting algorithm reorganizes a collection of items into some order as defined
by values intrinsic to the items.
Properties
Number of swaps required
Number of comparisons - represented using “big-o” notation
Stability - it’s stable when relative order of the equal items are
maintained.
Recursive or iterative
Amount of extra space
Bubble sort
Makes multiple passes through a collection and compare adjacent items to reorder
those.
Selection sort
Iterates through the list to find the smallest (or highest) value. Swaps its
position with the first element. Then redo this starting from index 1. And
repeat.
Insertion sort
Maintains a sorted sublist in the lower positions in the list. Each item picked
from the unsorted sublist is inserted into the sorted sublist.
Shell sort
A specific “gap” is chosen. Start from any index (which is smaller than gap),
and use insertion sort to sort the elements that are gap number of indices away.
Redo this after reducing the gap. Repeat until the gap eventually becomes 1.
The performance depends on the sequence of gaps chosen.
Merge sort
Recursive algorithm that continually splits a list in half.
If the list is empty or has one item, it is sorted
If the list has more elements, the list is split in the middle and merge sort
is recursively used on those parts
Once sorted, the halves are combined to create a new, sorted list
Quick sort
Recursive algorithm that use the divide and conquer strategy to continually
split a list around a selected value called the split point.
Similar to selection sort where a search is done to find the item with the
minimum value and this item is placed at the beginning of the list. The same
process is repeated for remaining items.
Steps:
A max-heap is built from the input data
Largest item is stored at the root of the heap. Replace it with the last item
of the heap.
Size of the heap is reduced by 1
Heapify the root of the tree
Repeat steps 2-4 until the size of the heap is greater than 1.
The heapify procedure can be applied to a node only if its children nodes are
heapified. So the heapification must be performed in the bottom-up order.