1. Exam Points
- Analyze the
behaviorof a recursive algorithm.- Analyze the
resultof a recursive algorithm.- Analyze the
resultof implementingrecursive binary searching.- Analyze
how many times divide or mergewill be executed inmerge sort.
2. Knowledge Points
(1) Use Recursion for Searching and Sorting
Recursioncan be used totraverseString objects, arrays, and ArrayList objects.- Commonly sued
searching algorithms:Linear Search: check each element in order, the search can start from either end (first to last, last to first), applies to any list.
Binary Search: (apply only to sorted list) : start from middle, cut in half for each round, applies only to sorted list.
(2) Binary Search
- Data must be in
sortedorder to use thebinary search algorithm. Binary searchstarts at the middle of a sorted array or ArrayList and eliminates half of the array or ArrayList in each recursive call until the desired value is found or all elements have been eliminated.- Binary search is
typically more efficientthan linear search. - The binary search algorithm can be written either
iterativelyorrecursively. Process demonstration:
- Code implementation using recursion:
// return the index of the target if found // or return arr.length if not found public static int binarySearch(int[] arr, int low, int high, int target) { int mid = (low + high) / 2; // find the index of the middle element if (low > high) { // if low is greater than high, end recursion return low; } else if (target > arr[mid]) { // if target is greater, search in the second half return binarySearch(arr, mid + 1, high, target); } else if (target < arr[mid]) { // if target is lesser, search in the first half return binarySearch(arr, low, mid - 1, target); } else { // arr{mid] == num // if target is found, return its index return mid; } } public static void main(String[] args) { int[] data = { 1, 2, 3, 4, 5 }; // here target is 2 int indexOfTarget = binarySearch(data, 0, data.length - 1, 2); System.out.println(indexOfTarget); }
(3) Merge Sort
Merge sortis a recursive sorting algorithm that can be used to sort elements in an array or ArrayList.- Merge sort
repeatedly dividesan array into smaller subarrays until each subarray is one element andthen recursively mergesthe sorted subarrays back together in sorted order to form the final sorted array. Process demonstration:
\