I've written out a recursive method for finding a single item in an array which is not repeated (whereas all other items are in pairs and next to one another). My question is, can this be done without recursion (perhaps with a while loop) and is using a loop within the function more effective (in terms of memory) than just using recursion?
Current solution:
function findSingularElement(arr, low, high) {
// base cases
if (arr.length < 3) return console.log('Invalid length of array.');
if (low > high) return;
if (low == high) return console.log(arr[low]);
var mid = low + (high - low) / 2;
if (mid % 2 === 0) {
if (arr[mid] == arr[mid + 1]) {
return findSingularElement(arr, mid + 2, high);
} else {
return findSingularElement(arr, low, mid);
}
} else {
if (arr[mid] == arr[mid - 1]) {
return findSingularElement(arr, mid + 1, high);
} else {
return findSingularElement(arr, low, mid - 1);
}
}
}
var array = [1, 1, 3, 3, 4, 5, 5, 7, 7, 8, 8];
Thank you.
lowandhighand loop whilelow <= high.4?4.