Programming - 7 - Algorithms Flashcards

1
Q

An algorithm is the process of solving a problem in terms of…

A
  • actions to exectute
  • order in which these actions are executed
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Binary Search code

A

public int binaryS (int val ) {

int low = 0

int high = data.length-1;

while( high>= low) {

int middle = (low+high)/2;

if (val == data[middle]) return middle;

else if (val < data[middle]) high = mddle - 1;

else

low = middle+1;

}

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

What sorts should you know?

A
  • Selection sort: find the smallest val, swap wit the first, find 2nd smallest, swap with 2nd etc
  • Bubble sort: compare adjacent elements, swap them if in wrong order. Repeat until sorted.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Selection sort and bubble sort code

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

Complexity: What does Big O notation describe

A

Describes worst case case run time (function of size n)

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

Different types of complexities in terms of Big O

A
  • O(1)
    • constant number of comparisons
  • O(n)
    • linear run time (of the order n), linear search
  • O(log(n))
    • logarithmic run time (binary search)
  • O(n2)
    • quadratic run time (check if any element is duplicated in the array)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the complexity of Selection Sort?

A
  • Outer “i” loop controls iterations of the inner one over remaining elements
  • inner loop does n- comparisons, then n-e,…. total is 1+2+…+(n-1)
    • (n2-n/2) = O(n2)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Bubble Sort Complexity

A
  • Inner for loop runs until outer while loop is stopped
  • inner does n-1 comparisons for n passes → n*(n-1) = n2 - n = O(n2)
  • works well in “almost-sorted” arrays
    *
How well did you know this?
1
Not at all
2
3
4
5
Perfectly