4.17 Recursive Searching and Sorting

4 阅读1分钟

1. Exam Points

  • Analyze the behavior of a recursive algorithm.
  • Analyze the result of a recursive algorithm.
  • Analyze the result of implementing recursive binary searching.
  • Analyze how many times divide or merge will be executed in merge sort.

2. Knowledge Points

(1) Use Recursion for Searching and Sorting

  • Recursion can be used to traverse String 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.
      image.png
    • Binary Search: (apply only to sorted list) : start from middle, cut in half for each round, applies only to sorted list.
      image.png

(2) Binary Search

  • Data must be in sorted order to use the binary search algorithm.
  • Binary search starts 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 efficient than linear search.
  • The binary search algorithm can be written either iteratively or recursively.
  • Process demonstration:
    image.png
  • 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 sort is a recursive sorting algorithm that can be used to sort elements in an array or ArrayList.
  • Merge sort repeatedly divides an array into smaller subarrays until each subarray is one element and then recursively merges the sorted subarrays back together in sorted order to form the final sorted array.
  • Process demonstration:
    \ image.png

3. Exercises