Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find the middle element of an array using recursion JavaScript
We are required to write an array function, say findMiddle that returns the middlemost element of the array without accessing its length property and without using any kind of built-in loops. If the array contains an odd number of elements, we return the one, middlemost element, or if the array contains an even number of elements, we return an array of two middlemost elements.
So, let's write the code for this function. As you've already guessed, we will be making use of recursion to find these elements. The code for the recursive function will be ?
How It Works
The recursive function works by:
- Incrementing an index counter recursively until it reaches the end of the array
- Using the final count to determine the array length
- Calculating the middle position(s) based on whether the length is odd or even
Example
const arr = [1, 2, 3, 4, 5, 6, 7];
const array = [1, 2, 3, 4, 5, 6, 7, 8];
const findMiddle = (arr, ind = 0) => {
if(arr[ind]){
return findMiddle(arr, ++ind);
};
return ind % 2 !== 0 ? [arr[(ind-1) / 2]] : [arr[(ind/2)-1], arr[ind/2]];
};
console.log(findMiddle(arr));
console.log(findMiddle(array));
Output
[ 4 ] [ 4, 5 ]
Step-by-Step Breakdown
Let's trace through the execution for better understanding:
const traceMiddle = (arr, ind = 0) => {
console.log(`Checking index ${ind}, value: ${arr[ind]}`);
if(arr[ind]){
return traceMiddle(arr, ++ind);
};
console.log(`Array length determined: ${ind}`);
const isOdd = ind % 2 !== 0;
console.log(`Is odd length: ${isOdd}`);
if(isOdd) {
const middleIndex = (ind-1) / 2;
console.log(`Middle index: ${middleIndex}`);
return [arr[middleIndex]];
} else {
const leftMiddle = (ind/2)-1;
const rightMiddle = ind/2;
console.log(`Middle indices: ${leftMiddle}, ${rightMiddle}`);
return [arr[leftMiddle], arr[rightMiddle]];
}
};
console.log("Result:", traceMiddle([1, 2, 3, 4, 5]));
Output
Checking index 0, value: 1 Checking index 1, value: 2 Checking index 2, value: 3 Checking index 3, value: 4 Checking index 4, value: 5 Checking index 5, value: undefined Array length determined: 5 Is odd length: true Middle index: 2 Result: [ 3 ]
Key Points
- The recursion stops when
arr[ind]is undefined (end of array) - For odd-length arrays: middle index =
(length-1) / 2 - For even-length arrays: two middle indices =
(length/2)-1andlength/2 - No built-in length property or loops are used
Conclusion
This recursive approach cleverly determines array length by counting elements, then calculates middle positions mathematically. It returns a single element for odd-length arrays or two middle elements for even-length arrays.
