Chapter 5 Algorithms Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

how to compare all values in 1D array

A

double for loop, triangular pattern

for(int i = 1; i < n; i++)
for(int j = 0; j<i; j++)
if(a[i] = a[j])
count++;

Total number of comparisons is 1 + 2 + . . . + (n-1) = n(n-1)/2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
Insert in Order
//shifts values a[k]. /// . a[n-1] apporpirately into a[k+1}, ...,a[n] and inserts newValue into a[k] so that the ascending order is prserved
//precondition: a[0]
A

void insertInOrder (int[]a, int n, int newValue){

//shift values to the right by one until you find the place to insert:

int k = n;
while( k>0 &amp;&amp; a[k-1] > newValue){
a[k] = a[k-1];
k--;
}
a{k] = newValue;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Loop invariant

A

an assertion about the loop that is

(1) relevant to the purpose of hte loop
(2) holds true before and after each iteration through the loop

if you can establish that an assertion is true before the first iteration, and also prove that for any iteration if the assertion is true before that iteration it will remain true after that iteration, then your assertion is a loop invariant.

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

loop invariant question

Consider the following code segment:

int count = 0; int n = 41; int = 2;
while (k

A

C.

Think about it. and or read page 101 of Be Prepared

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

How does sequential search work(in finding the value “target” in the array a in the range [a[0], a[n-1]])?

A
public int sequentialSearch(int[]a a, int n, int target){
  for(int k = 0; k < n; k++){
     if(a[k] == target)
      return k;
  }
  return -1;
}

Sequential Search works for any array: the values in the array may be in ramdom order. f an array is sorted (that is, if its elements are arranged in ascending or descending order), then Binary Search is a much more efficient method.

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

Binary Search

A

Divide and conquer method for quickly finding a target value in a sorted array. Suppose the array is sorted in ascending order. We take an aelement in the middle (or approximately in the middle) of te array and compare it to the target. If they are equal< we’re done. If the target is grater, we continue the search in the right half of the array; if it’s smaller we continue in the left half;

public int binarySearch(int[]a a, int n, int target){
int left = 0, right = n -1, middle;

while(left < a[middle])
right = middle - 1;// continue search in the left half
else left = middle +1;//continue search in the right half
}
return -1;

Binary SEarch in an array of 2^ k - 1 elements requires at most k iterations.
Book says “binary Saerchi n an array of n elements requires log base 2 of n iterations.

But I say it should be log base 2 of n+1 iterations. I may be wrong I would think that If you have to compare 30 elements it would take 5 iterations (32 = 2^ 5). if you have to compare 32 elements it would take 6 comparisons. In other words Binary Search in an array of n elements ceiling(log(base2, n+1)) iterations. Eg. for 32 elements it would take log base 2 of 33, which equals 5.04, so we round up to 6.

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

Suppose that two programs, one using Binary Search and the other using Sequential Search, take (on average) the same amount of time to find a random target value in a sorted array of 30 elements. Rougthly how much faster than the sequential Search program will hte Binary search program run on an array of 1000 elemetns?

A

Binary Search takes 5 iterations for 30 elements (32 = 2^ 5) and 10 iterations for 1000 elements (1024 = 2^ 10). So binary Search iwllrun roughly two times longer on a 1000element array than on a 30 element array. sequential search will run roughly 33 times longer (1000 = 30 * 33). On 1000 elements, Binary Search will be 33/2 = 16.5 times faster.

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

Sorting, as opposed to searching means

A

arranging a list of items in ascending or descending order, according to hte avlues of the items or some key that is part of an item

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

Selection Sort and Insertion Sort are called

A

quadratic sorts

becaues they use two straihtforward nested loops and hte number of required comparison is approximately proportional to n^ 2.

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

Linear search

A

also known as sequential search

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

Selection Sort

A

Sort of like a triangular search. It finds the largest of the unsorted elements and puts the largest at the at the top of the unsorted elements via swapping. It then continues to find the largest in the remaining unsorted elements and so on.

You could do the same with minimums.

//array is range a[0], a[n-1]
public void selectionSort(int[]a, int n)
{
int maxpos;
for(int k = n; k >= 2; k--){
maxPos = 0;
for (int i =1; i < k; i++){
if (a[i] > a[maxpos])
  maxPos = i;
}
//swap a[maxPos], a[k-1]
int tem = a[maxPos]; a[maxPos] = a,k-s]; a[k-1] = temp;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

The total number of comparisons in Selection sort is always

A

the same.

(n-1) + (n-2) + … + 1 = n(n-1)/2

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

Insertion Sort

A

The Insertion Sort works by arranging the first two elements in order; then
placing the third element in its correct position relative to the first two elements; and
continuing that way until all elements have been placed.

After p steps, the first p+1 elements are arranged in order.

package com.java2novice.algos;

public class MyInsertionSort {

public static void main(String[] args) {

    int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
    insertionSort(input);
}

private static void printNumbers(int[] input) {

    for (int i = 0; i < input.length; i++) {
        System.out.print(input[i] + ", ");
    }
    System.out.println("\n");
}
    public static void insertionSort(int array[]) {
        int n = array.length;
        for (int j = 1; j < n; j++) {
            int key = array[j];
            int i = j-1;
            while ( (i > -1) && ( array [i] > key ) ) {
                array [i+1] = array [i];
                i--;
            }
            array[i+1] = key;
            printNumbers(array);
        }
    }
}

Output:
2, 4, 9, 6, 23, 12, 34, 0, 1,

2, 4, 9, 6, 23, 12, 34, 0, 1,

2, 4, 6, 9, 23, 12, 34, 0, 1,

2, 4, 6, 9, 23, 12, 34, 0, 1,

2, 4, 6, 9, 12, 23, 34, 0, 1,

2, 4, 6, 9, 12, 23, 34, 0, 1,

0, 2, 4, 6, 9, 12, 23, 34, 1,

0, 1, 2, 4, 6, 9, 12, 23, 34,

public static void insersionSort(int[] input){
int key;
for(int i=1;i-1&&(input[j]>key)){
input[j+1]=input[j];
input[j]=key;
j--;
}
}
for(int i=0;i
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Worst case for Be Prepared’s implementation of insertion sort (p105) is

average case
best case

A

when the array is sorted in reverse order

of comparisons = 1 + 2 + … + (n-1) = n(n-1)/2

average case = n(n-1)/4
best case = n-1

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

Binary Search can also be implemented

A

recursively

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

Mergesort takes how many comparisons

A

on average: nlog n, as opposed to n^ 2 comparisons in quadratic sorts

this difference can be very signifacnt for large arrays

17
Q

MergeSort

A

divide the array into two approximately equal halves
sort (recursively) each half, then merge them together into one sorted array. Mergesort usually requires a temporary array for holding the two soretd halves before they are merged back into hte original space.

//sorts values a[n1], . . . , a[n2] in ascending order
//precondition: 0 a[m+1])
  merge (a,n1,m, n2);

A typical implementatino of Mergesort doesn’t skip hte work even when the array is already sorted.

18
Q

Data Organization Questions

A

.