Algorithms Flashcards

1
Q

Insertion Sort Code

A

import java.io.;
import java.util.
;

public class Solution {

public static void insertionSort(int[] A){
    for(int i = 1; i < A.length; i++){
        int value = A[i];
        int j = i - 1;
        while(j >= 0 &amp;&amp; A[j] > value){
            A[j + 1] = A[j];
            j = j - 1;
        }
        A[j+1] = value;
    }

    printArray(A);
}

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

import java.io.;
import java.util.
;

public class Solution {

public static void \_\_\_\_\_\_\_\_\_\_(int[] A){
    for(int i = 1; i < A.length; i++){
        int value = A[i];
        int j = i - 1;
        while(j >= 0 &amp;&amp; A[j] > value){
            A[j + 1] = A[j];
            j = j - 1;
        }
        A[j+1] = value;
    }

    printArray(A);
}

}

A

Insertion Sort

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Insertion Sort Pseudocode

A

Consider 1st item sorted
Compare next item with previous
Swap if necessary keeping subarray sorted
Continue up array until all are sorted

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Quicksort Code

A

import java.io.;
import java.util.
;

public class Solution {

 public static int[] quickSort(int[] ar, int lo, int hi){
    if(lo
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Quicksort Steps

A

Take first element of the array as the partition
Break up the list into left, equal, and right elements
If left or right is greater than 1 element, continue to partition
Merge the left, equal, and right arrays
Continue until array is sorted

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
algorithm quicksort(A, lo, hi) is
    if lo < hi then
        p := partition(A, lo, hi)
        quicksort(A, lo, p - 1)
        quicksort(A, p + 1, hi)
algorithm partition(A, lo, hi) is
    pivot := A[hi]
    i := lo
    for j := lo to hi do
        if A[j] < pivot then
            swap A[i] with A[j]
            i := i + 1
    swap A[i] with A[hi]
    return i
A

Quicksort

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Binary Search Steps

A
  1. Choose lo = 0, hi = n-1
  2. Find mid point (lo+hi)/2 and check if mid value is equal to target
  3. If mid value is less than, set lo = mid + 1 and repeat step 4. if mid value is greater than, set hi = mid - 1 and repeat.
  4. Return target index = mid
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Binary Search Code

A

public class Solution {
public static int binarySearch(int[] arr, int target){
int lo = 0, hi = arr.length -1, mid = 0;
while(lo < hi){
mid = (lo + hi)/2;
if(arr[mid]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly