Binary trees Sorting Exceptions Tirgul 13 Binary trees Sorting Exceptions
Binary search trees vs. arrays Unsorted array: Insertion Deletion Lookup Sorted array: Binary search tree: O(1) O(1) O(n) O(n) O(n) O(logn) O(logn) We’ll see today O(logn)
Removing a node Last week we saw how to add and search in binary search trees. Remove operation is more complicated. Basically, it can be divided into two stages: search for a node to remove. if the node is found, run remove algorithm.
Remove algorithm First stage is identical to algorithm of search, except we should track the parent of the current node. Second part is more tricky. There are three cases: Node to be removed has no children. Node to be removed has one child. Node to be removed has two children.
Node to be removed has no children Simple - algorithm sets corresponding link of the parent to NULL and disposes the node.
Node to be removed has one child Node is cut from the tree and algorithm links single child (with it's subtree) directly to the parent of the removed node.
Node to be removed has two children (1) This is the most complex case. We are going to use the idea, that the same set of values may be represented as different binary-search trees. For example those BSTs:
Node to be removed has two children (2) To transform first tree into second one, we can do following: choose minimum element from the right subtree (19 in the example); replace 5 by 19; hang 5 as a left child.
Node to be removed has two children (3) The same approach can be utilized to remove a node, which has two children: find a minimum value in the right subtree. replace value of the node to be removed with found minimum. Now, right subtree contains a duplicate! apply remove to the right subtree to remove a duplicate. Notice, that the node with minimum value has no left child and, therefore, it's removal may result in first or second cases only.
Node to be removed has two children (4) Find minimum element in the right subtree of the node to be removed. In current example it is 19.
Node to be removed has two children (5) Replace 12 with 19. Notice, that only values are replaced, not nodes. Now we have two nodes with the same value. Remove 19 from the left subtree.
Remove - Java code (1) public class BinarySearchTree { … … public boolean remove(int value) { if (root == null) return false; else { if (root.getValue() == value) { BSTNode auxRoot = new BSTNode(0); auxRoot.setLeftChild(root); boolean result = root.remove(value, auxRoot); root = auxRoot.getLeft(); return result; } else { return root.remove(value, null); } } } } Special case: Remove the root
Remove - Java code (1) public class BSTNode { … public boolean remove(int value, BSTNode parent) { if (value < this.value) { if (left != null) return left.remove(value, this); else return false; } else if (value > this.value) { if (right != null) return right.remove(value, this); } else { if (left != null && right != null) { this.value = right.minValue(); right.remove(this.value, this); } else if (parent.left == this) { parent.left = (left != null) ? left : right; } else if (parent.right == this) { parent.right = (left != null) ? left : right; } return true; } } public int minValue() { if (left == null) return value; else return left.minValue(); } Find the node to remove If two children: copy the minimum from the node’s subtree and remove the minimum. If one child: remove it
Sorting algorithms Algorithm Best Worst Memory Stable Bubble sort O(n) Yes Insertion sort Selection sort No Merge sort O(nlogn) Quick sort O(logn) ? Counting sort O(n+k) http://www.sorting-algorithms.com/
Merge sort To sort A[p .. r]: Divide by splitting into two subarrays A[p ..q] and A[q + 1 .. r], where q is the halfway point of A[p .. r]. Conquer by recursively sorting the two subarrays A[p .. q] and A[q + 1 ..r]. Combine by merging the two sorted subarrays A[p .. q] and A[q + 1 .. r] to produce a single sorted subarray A[p .. r]. To accomplish this step, we’ll define a procedure MERGE(A, p, q, r). The recursion bottoms out when the subarray has just 1 element, so that it’s trivially sorted.
Merge sort
Example Bottom-up view for n = 8
Merging What remains is the MERGE procedure. Input: Array A and indices p, q, r such that p ≤ q < r. Subarray A[p ..q] is sorted and subarray A[q + 1 ..r] is sorted. By the restrictions on p, q, r, neither subarray is empty. Output: The two subarrays are merged into a single sorted subarray in A[p .. r]. We implement it so that it takes Θ(n) time, where n = r - p + 1 = the number of elements being merged. Just like merging two sorted piles of cards
Merging
Example - A call of MERGE(9, 12, 16)
MERGE Running time of MERGE The first two for loops take Θ(n11 + n222) = Θ(n) time. The last for loop makes n iterations, each taking constant time, for Θ(n) time. Total time: Θ(n).
Analyzing divide-and-conquer algorithms Use a recurrence equation (more commonly, a recurrence) to describe the running time of a divide-and-conquer algorithm. Let T(n) =running time on a problem of size n. If the problem size is small enough (say, n ≤ c for some constant c), we have a base case. The brute-force solution takes constant time: Θ(1). Otherwise, suppose that we divide into a subproblems, each 1/b the size of the original. (In merge sort, a =b = 2.)
Analyzing merge sort For simplicity, assume that n is a power of 2 ⇒ each divide step yields two subproblems, both of size exactly n/2i. The base case occurs when n = 1. When n ≥ 2, time for merge sort steps: Divide: Just compute q as the average of p and r ⇒ Θ(1). Conquer: Recursively solve 2 subproblems, each of size n/2 ⇒ 2T(n/2). Combine: MERGE on an n-element subarray takes Θ(n) time ⇒ Θ(n).
Solving the merge-sort recurrence Let c be a constant that describes the running time for the base case and also is the time per array element for the divide and conquer steps. We rewrite the recurrence as
Solving the merge-sort recurrence Draw a recursion tree, which shows successive expansions of the recurrence. For the original problem, we have a cost of cn, plus the two subproblems, each costing T(n/2):
Solving the merge-sort recurrence For each of the size-n/2 subproblems, we have a cost of cn=2, plus two subproblems, each costing T(n/4):
Solving the merge-sort recurrence Continue expanding until the problem sizes get down to 1: Why is the height logn?
Solving the merge-sort recurrence Each level has cost cn. The top level has cost cn. The next level down has 2 subproblems, each contributing cost cn/2. … There are log2n + 1 levels (height is log2n). Use induction. Base case: n = 1 ⇒ 1 level, and log21 = 1 + 0 + 1 = 1. Inductive hypothesis is that a tree for a problem size of 2i has log22i + 1 = i + 1 levels.
Solving the merge-sort recurrence Because we assume that the problem size is a power of 2, the next problem size up after 2i is 2i+1 A tree for a problem size of 2i+1 has has one more level than the size-2i tree ⇒ i + 2 levels Since log22i+1 + 1 = i + 2, we’re done with the inductive argument Total cost is sum of costs at each level. Have log2n + 1 levels, each costing cn ⇒ total cost is cn log2n + cn. Ignore low-order term of cn and constant coefficient c⇒ Θ(n lg n)
Solving the merge-sort recurrence Compared to insertion sort Θ(n2) worst-case time), merge sort is faster. On small inputs, insertion sort may be faster. We can understand how to solve the merge-sort recurrence without the master theorem.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary
Introduction Users have high expectations for the code we produce. Users will use our programs in unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected ways during execution
Introduction It is our responsibility to produce quality code that does not fail unexpectedly. Consequently, we must design error handling into our programs.
Errors and Error Handling An Error is any unexpected result obtained from a program during execution. Unhandled errors may manifest themselves as incorrect results or behavior, or as abnormal program termination. Errors should be handled by the programmer, to prevent them from reaching the user.
Errors and Error Handling Some typical causes of errors: Memory errors (i.e. memory incorrectly allocated, memory leaks, “null pointer”) File system errors (i.e. disk is full, disk has been removed) Network errors (i.e. network is down, URL does not exist) Calculation errors (i.e. divide by 0)
Errors and Error Handling More typical causes of errors: Array errors (i.e. accessing element –1) Conversion errors (i.e. convert ‘q’ to a number) Can you think of some others?
Errors and Error Handling Exceptions – a better error handling Exceptions are a mechanism that provides the best of both worlds. Exceptions act similar to method return flags in that any method may raise and exception should it encounter an error. Exceptions act like global error methods in that the exception mechanism is built into Java; exceptions are handled at many levels in a program, locally and/or globally.
Exceptions What are they? An exception is a representation of an error condition or a situation that is not the expected result of a method. Exceptions are built into the Java language and are available to all program code. Exceptions isolate the code that deals with the error condition from regular program logic.
Exceptions How are they used? Exceptions fall into two categories: Checked Exceptions Unchecked Exceptions Checked exceptions are inherited from the core Java class Exception. They represent exceptions that are frequently considered “non fatal” to program execution Checked exceptions must be handled in your code, or passed to parent classes for handling.
Exceptions How are they used? Unchecked exceptions represent error conditions that are considered “fatal” to program execution. You do not have to do anything with an unchecked exception. Your program will terminate with an appropriate error message.
Exceptions Examples: Checked exceptions include errors such as “file not found” and “number format conversion”. Unchecked exceptions include errors such as “null pointer”.
Exceptions How do you handle exceptions? Exception handling is accomplished through the “try – catch” mechanism, or by a “throws” clause in the method declaration. For any code that throws a checked exception, you can decide to handle the exception yourself, or pass the exception “up the chain” (to a parent class).
Exceptions How do you handle exceptions? To handle the exception, you write a “try-catch” block. To pass the exception “up the chain”, you declare a throws clause in your method or class declaration. If the method contains code that may cause a checked exception, you MUST handle the exception OR pass the exception to the parent class (remember, every class has Object as the ultimate parent)
Coding Exceptions Try-Catch Mechanism Wherever your code may trigger an exception, the normal code logic is placed inside a block of code starting with the “try” keyword: After the try block, the code to handle the exception should it arise is placed in a block of code starting with the “catch” keyword.
Coding Exceptions Try-Catch Mechanism You may also write an optional “finally” block. This block contains code that is ALWAYS executed, either after the “try” block code, or after the “catch” block code. Finally blocks can be used for operations that must happen no matter what (i.e. cleanup operations such as closing a file) Exception Handling in Java June 14, 2001
Coding Exceptions Example try { … normal program code } catch(Exception e) { … exception handling code } Exception Handling in Java June 14, 2001
Coding Exceptions Passing the exception In any method that might throw an exception, you may declare the method as “throws” that exception, and thus avoid handling the exception yourself Example public void myMethod throws IOException { … normal code with some I/O } Exception Handling in Java June 14, 2001
Coding Exceptions Types of Exceptions All checked exceptions have class “Exception” as the parent class. You can use the actual exception class or the parent class when referring to an exception Where do you find the exception classes? Reference books such as “Java in a Nutshell” (O’Reilly, 2001), or the Java Documentation.
JAVA Exception hierarchy Blue: checked exceptions Red: Unchecked exceptions
Example: catch general exception try{ int[] myArray=null; System.out.println(myArray[3]); } catch(Exception e){ System.out.println(e.getMessage()); e.printStackTrace(); NullPointerException !
Example: several catch statements try{…} catch(NullPointerException npe){ System.out.println("got null pointer Exception"); } catch(Exception e){ System.out.println("got Exception");
Checked exceptions must be checked or propagated! class Example2{ public static void test (){ try{ int message=System.out.read(); System.out.pribtln("successful read"); } Catch (IOEXception exception){ System.out.println("unsuccessful read"); class Example2{ public static void test () throws IOException{ int message=System.out.read(); System.out.pribtln("successful read"); }
Writing a new exception public class MyException extends Exception} public MyException (String error){ super(error); } { public static void foo(int n) throws MyException{ if (n<5) throw new MyException(“n could not be negative in foo”); System.out.println(“Thank you and have a good day”);
Using the execption int n = (int)(Math.random()*10); try{ foo(n); } catch (MyException e){ e.printStackTrace();
Summary Exceptions are a powerful error handling mechanism. Exceptions in Java are built into the language. Exceptions can be handled by the programmer (try-catch), or handled by the Java environment (throws).