Sorting
It is one of the most common tasks in data analysis.
Examples:
- Print out a collection of employees sorted by salary.
- Print out a list of names in alphabetical order.
Selection sort repeatedly finds the smallest element in the unsorted tail region of a list and moves it to the front.
More info here (Selection Sort).
How Fast is an Algorithm?
With an array of size n, count how many primitive operations are needed.
- To find the smallest, visit elements + 2 operations for the swap.
- To find the next smallest, visit elements + 2 operations for the swap.
- The last term is 2 elements visited to find the smallest + 2 operations for the swap.
The number of operations:
- .
- Which can be simplified to .
- is small compared to , so we can ignore it.
- We can also ignore the , we use the simplest expression of the class.
- So it is simplified to .
- Using Big-O notation:
- .
Search Algorithm
Check for an element from any data structure where it is stored.
Classed into two categories:
- Sequential Search (linear search).
- The list is traversed sequentially, and every element is checked.
- The list does not need to be sorted.
- Interval Search (binary search).
- A divide and conquer algorithm.
- The list must be sorted.
More info here (Graph Search).
Binary Search vs Linear Search
Binary search is an algorithm:
- elements -> elements -> elements -> … -> 1 element.
Linear search algorithm of order .
Which algorithm is faster?
- Binary search algorithm is much faster, but it only works on sorted data.
Examples of binary search:
- Spell checkers, phone books, dictionaries…