Algorithms_ Searching and Sorting Cheatsheet _ Codecademy
Algorithms_ Searching and Sorting Cheatsheet _ Codecademy
binary_search(sorted_list, left_p
if (left_pointer >= right_point
base case 1
mid_val and mid_idx defined her
if (mid_val == target)
base case 2
if (mid_val > target)
recursive call with left poin
if (mid_val < target)
recursive call with right poi
Updating pointers in a recursive binary search
In a recursive binary search, if the value has not been function binarySearchRecursive(array,
found then the recursion must continue on the list by
first, last, target) {
updating the left and right pointers after comparing the
target value to the middle value. let middle = (first + last) / 2;
If the target is less than the middle value, you know the // Base case implementation will be in
target has to be somewhere on the left, so, the right
pointer must be updated with the middle index. The left
here.
pointer will remain the same. Otherwise, the left
pointer must be updated with the middle index while if (target < array[middle]) {
the right pointer remains the same. The given code
block is a part of a function
return binarySearchRecursive(array,
binarySearchRecursive() . first, middle, target);
} else {
return binarySearchRecursive(array,
middle, last, target);
}
}
Binary Search
}
}
public static void main(String[] args)
{
}
}
Insertion Sort Nested Loops
Insertion sort uses nested loops. The inner loop class InsertionSort {
iterates through the list of items that are already sorted
looking for the correct place to insert the most recent
public static void sort(int[] array) {
unsorted item. This loop happens n times - once for // outer loop iterates through input
each item that needs to be inserted. array starting with second element
for (int i = 1; i < array.length; i++)
{
// store value of current element
// inner loop
while (j >= 0 && array[j] > current)
{
// compare current element to
predecessor(s)
}
// move the greater element(s) one
position to make space for swapped
element
}
}
}
In the case of an ascending array, the best case int[] ascendingNumbers = {2, 4, 6, 8};
scenario, the runtime of insertion sort is O(n). As each
insertionSort(ascendingNumbers);
element gets picked for insertion into the sorted list, it
will only take one comparison to find the correct place // sort second element - 4 is greater
to insert the new item. 1 comparison will happen n than 2 - no shift or further comparisons
times, for a total runtime of O(n).
// sort third element - 6 is greater than
4 - no shift or further comparisons
// sort fourth element - 8 is greater
than 6 - no shift or further comparisons
Java Insertion Sort Runtime
In the case of a descending array, our worst case int[] descendingNumbers = {8, 6, 4, 2};
scenario, insertion sort will have to make approximately
insertionSort(descendingNumbers);
n^2 comparisons. This happens when the list to sort is
in perfect reverse order. All n items that need to be // result of first sort - {6, 8, 4, 2}
inserted into the sorted section of the list will be // result of second sort - {4, 6, 8, 2}
compared to every item in the already sorted section
// comparisons to sort last element - 2
of the list.
is less than 8, 2 is less than 6, 2 is
less than 4, insert 2
Selection Sort Algorithm
int currentMinimumIndex = i;
for (int j = i + 1; j < arr.length;
j++) {
if (arr[j] <
arr[currentMinimumIndex]) {
currentMinimumIndex = j;
}
}
int temp =
arr[currentMinimumIndex];
arr[currentMinimumIndex] = arr[i];
arr[i] = temp;
}
}
Selection sort makes use of nested for loops. The inner public static void selectionSort (int
for loop finds the smallest number from the section of
arr[]) {
the unsorted array and moves it to the end of the
sorted section of the array. The outer for loop makes
this process happen n times - once for each element //for loop to loop through all
that needs to be put into the sorted section of the
unsorted elements
array
for (int i = 0; i < size - 1; i++) {
// for loop to find the smallest
value of unsorted elements
for (int j = i + 1; j <
arr.length; j++) {
// Code that keeps track of
the smallest value
}
// Code that swaps the smallest
value to the correct place
}
Nested loops are generally an indicator of quadratic public static void selectionSort (int
complexity. This means that as the number of elements
arr[]) {
n increases, the running time increases quadratically.
This means that if n doubles, we know that sorting
time will quadruple, resulting in a runtime of O(n^2) due // nested for loop indicates runtime
to the nested loop structure.
of O(n^2)
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j <
arr.length; j++) {
}
}
}
Selection Sort Number of Comparison Statements
In both best case and worst case scenarios, selection // worst case scenario
sort makes approximately n^2 comparisons. Even if the
int[] inputArray1 = { 19, 15, 12, 7 };
list is already sorted, the inner for loop will have to
make n comparisons to find the smallest remaining selectionSort(inputArray1);
unsorted item. // determine 1st index
// compare 19 to 15, then 15 to 12,
then 12 to 7
// 7 is the lowest value, swap with 19
// 3 comparisons were made
Sorting occurs as selection sort swaps the element in public static void selectionSort (int
the first position of the unsorted sub-list with the
arr[]) {
element with the lowest value in the remainder of the
unsorted sub-list.
// for loop to loop through all
unsorted elements
for (int i = 0; i < size - 1; i++) {
// for loop to find the smallest
value of unsorted elements
for (int j = i + 1; j < arr.length;
j++) {
// Code that keeps track of
the smallest value
}
// Code that swaps the smallest
value to the correct place
int temp =
arr[currentMinimumIndex];
arr[currentMinimumIndex] = arr[i];
arr[i] = temp;
}
}
Linear search will start with the first element and check
if it is a match for our target element, and will continue
the search till it finds a match. The steps are:
Step 1: Examine the current element in the list.
Step 2: If the current element is equal to the target
value, stop.
Step 3: If the current element is not equal to the target
value, check the next element in the list.
Continue steps 1 - 3 until the element is found or the
end of the list is reached.
if (target == array[mid]) {
return mid;
}
// code to run if `target` is
greater or lesser than `array[mid]`
}
return -1;
}
}
Iterative Binary Search Algorithm
return -1;
}
}
Linear search