THINK FIRST·CODE LATER

← All labs

Recursive helper methods on arrays

Problem

A recursive method on an array usually needs extra parameters (an index, or a range) that the caller should not have to supply. The solution is a pair: a public method with the natural signature, and a private recursive helper that carries the extra parameters.

Write ArrayRecursion with these pairs — no loops in any of them:

public helper
max(int[] a) max(a, high) — largest of a[0..high]
sum(int[] a) sum(a, from)
isSorted(int[] a) isSorted(a, i)
isPalindrome(int[] a) isPalindrome(a, low, high)
binarySearch(int[] a, int key) binarySearch(a, key, low, high)
indexOf(int[] a, int key) indexOf(a, key, from)
reverse(int[] a) reverse(a, low, high) — in place

main reads n, the n values and a key. It uses the binary search when the array is sorted and the linear search otherwise. For the input

7
3 8 15 15 23 42 57
23

the program prints

Largest: 57
Sum: 163
Sorted: true
Palindrome: false
Binary search for 23: index 4
Reversed in place: 57 42 23 15 15 8 3

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d1-8-data-1.txt

7
3 8 15 15 23 42 57
23
What your program must print for d1-8-data-1.txt
Largest: 57
Sum: 163
Sorted: true
Palindrome: false
Binary search for 23: index 4
Reversed in place: 57 42 23 15 15 8 3

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d1-8-data-1.txt

Windows PowerShell does not understand <:

Get-Content d1-8-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.