Sorting, Hashing, Recursion

Basic sorting algorithms, hashing via hashCode/equals, and recursion patterns.


Bubble sort swaps adjacent out-of-order pairs; selection sort takes the smallest remaining each pass; insertion sort inserts each value into a sorted prefix. Collections.sort orders a List via Comparable. Hashing maps keys to indices via hashCode(); equal objects must share a hash, so override hashCode() with equals(). Recursion: a method calling itself; a base case stops it. Examples: factorial, Fibonacci, binary search.

Example
int fact(int n) {
  return(n <= 1) ? 1 : n * fact(n - 1);
}
Video Lesson Open in new tab
Quiz
1. In a single pass of bubble sort over the whole array, the largest element of that pass is guaranteed to end up where?
2. What does selection sort do during each pass over the unsorted region?
3. Which call sorts a List<String> in ascending natural order?
4. According to the Java hashCode()/equals() contract, which statement must hold?
5. What stops a recursive method from calling itself forever?
6. A HashMap created with the no-argument constructor uses which initial capacity and load factor?
Coding Problems
1. Write a recursive Java method that returns the nth Fibonacci number where fib(0)=0 and fib(1)=1, then print fib(6).
Discussion

Login to join the discussion.


No comments yet.