Search algorithm is an algorithm which solves the problem of retrieving store information.
Wikipedia - Search AlgorithmsHow to solve the problem of searching billions pieces of data?
One of the simplest searches.
Find an item with a particular value in a sorted sequence.
Find 'J' in sequence:
[4, 5, J, 10, Q, K, A]
J is the 3rd element (index 2).
Find an item by repeatedly halving the search space.
To find the index of element e with a certain value:
What factors determine time?
N = number of items in sequence.
Since binary search algorithm splits array in half every time, at most log2N steps are performed.
Performance varies depending on sequence characteristics (distribution)
Why so important?
You do it all the time in real life
They're not in perfect order, but in a way that makes it easier for you to search for things
Many sorting algorithms for many types of data
There are lots of different types of data computers need to sort, just like in the real world
function swap(array, i, j) {
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
function selectionSort(array) {
for(var i = 0; i < array.length; i++) {
var min = i;
for(var j = i + 1; j < array.length; j++) {
if(array[j] < array[min]) {
min = j;
}
}
if(i !== min) {
swap(array, i, min);
}
}
return array;
}
Source
What is the best case?
What is the worst case?
They are the same! No matter what, selection sort has a time complexity of O(N^2)
Only requires 1 extra temporary variable. O(1)
All differ in performance, and performance often depends on data characteristics.
Wikipedia: Comparison of algorithm performance, Sorting Algorithms Visualization
A great resource to help visualize the different sorting algorithms:
Visualgo.netWhen is it best?
When is it best?
When is it best?
You have 6 stacks of mostly sorted papers. How would you sort them all together?
I focused on which type of data is good or bad for each sorting example, but each sorting algorithm also has its own space trade offs as well.
Arrays of arrays
Linear search for matrices
Find maximum element of each row in a matrix
Input : [1, 2, 3]
[1, 4, 9]
[76, 34, 21]
Output :
[3, 9, 76]
Input : [1, 2, 3, 21]
[12, 1, 65, 9]
[1, 56, 34, 2]
Output :
[21, 65, 56]
What is the time complexity?
O(n*m)
What is the space complexity?
O(n)
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
def get_data(self):
return self.data
def get_next(self):
return self.next_node
def set_next(self, new_next):
self.next_node = new_next
Trees - breadth first and depth first search
Trees - binary search