The debate: Using Recursion versus Not Using Recursion in a JavaScript Binary Search Algorithm for Arrays

I have come up with a recursive method to identify a unique item in an array (where all other items appear in pairs next to each other). I am wondering if it's possible to achieve the same result without recursion, perhaps using a while loop. Additionally, I am curious whether utilizing a loop within the function consumes less memory compared to recursion?

Solution at present:

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];

Appreciate any insights.

Answer №1

To eliminate recursion from your function, simply swap out recursive calls with appropriate variable assignments:

function findSingularElement1(arr) {
    if (arr.length < 3)
        throw('Invalid length of array.');

    var low = 0, high = arr.length - 1;

    while (low < high) {

        var mid = low + (high - low) / 2;

        if (mid % 2 === 0) {
            if (arr[mid] == arr[mid + 1]) {
                low = mid + 2;
            } else {
                high = mid;
            }
        } else {
            if (arr[mid] == arr[mid - 1]) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
    }
    return low == high ? arr[low] : null;
}

However, it appears that the entire approach you are taking is overly complex. You can easily identify an unpaired item using a simple loop:

for (var i = 0; i < array.length; i += 2)
    if (array[i] != array[i + 1])
        return array[i];

(Assuming the array is sorted, and each item occurs exactly once or twice).

Answer №2

Just for fun, here's my playful response!

let numArray = [2, 4, 7, 13, 15, 18, 22, 31, 39, 42, 57, 79];

function recursiveSearch(sortedArr, key, startIdx, endIdx) {
    let startIdx = startIdx || 0;
    let endIdx = endIdx || sortedArr.length;
    let midIdx = Math.floor((startIdx + endIdx) / 2);

    if (startIdx > endIdx) {
        return -1;
    }

    if (key === sortedArr[midIdx]) {
        return sortedArr[midIdx];
    } else if (key < sortedArr[midIdx]) {
        return recursiveSearch(sortedArr, key, startIdx, midIdx - 1);
    } else if (key > sortedArr[midIdx]) {
        return recursiveSearch(sortedArr, key, midIdx + 1, endIdx);
    }
}

let total = recursiveSearch(numArray, 15);

Answer №3

When it comes to using recursion in programming, there is always the option to replace it with loops. Recursion does have its benefits though, as it can make the code more straightforward and organized. In a binary search scenario, recursion can be swapped out for a loop by updating the base condition accordingly.

 function binarySearch(arr,ele){
  let low = 0;
  let high = arr.length-1;
  while(low<=high){
   let mid = Math.floor((low+high)/2) 
   if(arr[mid]==ele) 
     return true;
   else if(arr[mid]>ele)
     high = mid-1;
   else
     low = mid+1;
    }
  return false;
 }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The process in mocha does not execute when using await

"It" in the Mocha testing framework does not execute when using the await keyword. My approach involves employing functions for asynchronous file reading and then processing the test based on the returned value. I utilize these file read functions multipl ...

PHP - Determine the number of elements in an array by comparing it to another

I have an array structured like this: $array1 = array(Array('b','d'), Array('c','a'), Array('b','d'), Array('a','d'), ...

Showcasing interactive column titles by employing angularjs in an html table

After preparing my data, I aim to showcase it in an HTML table. However, a complication arises each time the $http service is called as it returns a varying number of columns (n). Essentially, I wish to have the first row of the data serve as column names, ...

Indicating that jQuery is not recognized despite the jQuery file being successfully loaded

Currently, I am working on an angular.js application where I have included the jQuery file. However, despite this inclusion, I am encountering an error message. Error Uncaught ReferenceError: jQuery is not defined(anonymous function) @ popup.js:1 File ...

Creating a smooth transition effect for a welcoming message using PHP upon logging in

In the given code snippet for setting a cookie on a website, the logic is such that it checks if the cookie with user's full name already exists. If it does, it immediately displays a welcome message to the user and redirects them to the home page aft ...

The Distinction Between "Q" and "q" in AngularJS and RequireJS

Currently, my project involves developing a single page application using AngularJS, Breeze, and RequireJS. While trying to configure AMD with requirejs to integrate Angular and Breeze, I ran into an issue related to Breeze's dependency on "q". Intere ...

The essence of the argument becomes muddled when implementing bind apply with arrays as arguments

I referenced this particular solution to create a new instance of a class by passing array arguments using the code snippet below: new ( Cls.bind.apply( Cls, arguments ) )(); However, I encountered an issue where one of my arguments is an array and the v ...

Inspect Element: JSON data is being displayed rather than the expected HTML source code

When inspecting the page source, I noticed that instead of the HTML page, the JSON response (which is essentially the table data) is being displayed. Initially, I was trying to find a way to retrieve the JSON response while still rendering the HTML page. T ...

Exploring querying techniques in Node.js

Hi there, I'm new to asking questions and I'm really hoping to find some answers here. I am just starting out with JavaScript so please explain things in simple terms. So here's my issue - I'm not sure how to properly query. - Should ...

Updates cannot be flushed while React is currently rendering

My goal is to display an alert using sweetalert2 when an error is returned by the API. To achieve this, I check if the error message is not empty in my render method and trigger the alert for the user accordingly. Upon submitting the form, an API call is ...

AngularJS: Implement ng-repeat directive to generate two separate HTML containers

I have a collection of items and I want to divide them into two separate containers. Is there a way to achieve this using ng-repeat? <div> <ul> <li>Some item</li> <li>Some item</li> <li&g ...

Changing image using setInterval() with class in p5.js

I'm currently tackling a project involving p5.js. My objective is to rotate images every X seconds, similar to how it was achieved in this example here. Nevertheless, I encountered an issue when attempting the same with a class object. The setInterv ...

Finding the index of a nested div element with a click event using jQuery

I'm currently working on a click event to retrieve the index of the outermost parent div, but I'm facing some difficulties in getting it to work. Here is a snippet showcasing a list of several divs: <div class="owl-item"> <div class= ...

Steps for creating checkboxes for individual table rows in HTML using embedded PHP and updating their values in a PostgreSQL database:1. Begin by iterating through each

I have already retrieved the data from the database. It is displayed on the HTML table, but it is currently in non-editable mode. I need to ensure that the data shown is accurate and update its Boolean value in the database. Otherwise, incorrect records sh ...

Choose rows from a NumPy array in a random manner depending on a specific condition

Assume there are 2 arrays of arrays, labels being 1D and data 5D with the first dimension being the same for both arrays. To simplify, let's consider labels having only 3 arrays: labels=np.array([[0,0,0,1,1,2,0,0],[0,4,0,0,0],[0,3,0,2,1,0,0,1,7,0]]) ...

Step-by-step guide to automatically check a checkbox when a field is updated

I'm currently working on a form that consists of 10 fields and 10 checkboxes. When I update a field, I want the relevant checkbox to be automatically checked. Instead of writing separate ON change functions for each field, I am seeking a more efficien ...

Transmit information from JavaScript to a servlet and receive a response in return

I'm new to using ajax and JavaScript. Currently, I have a simple jsp page containing HTML and an accompanying JavaScript file with all my functions defined. One of these functions sends JSON data to a servlet and now I need assistance in receiving th ...

Sort the observable data by a value returned from an API request

I am completely new to using RxJS and any assistance offered would be greatly appreciated! Within my component's HTML template, I am looking to create a radio button list. The values for this list are fetched from an observable using the async pipe. ...

Limit the number input to only allow values between 0 and 100

I am utilizing the Number input component from MUI, which includes Increment and Decrement buttons for adjusting numbers. Is there a method to limit the input to only accept values ranging from 0 to 100 ? Additionally, how can I decrease the width of the ...

Setting up the Angular 2 router to function from the /src subfolder

My goal is to create two separate subfolders within my project: src and dist. Here are the key elements of my application: root folder: C:\Server\htdocs\ app folder: C:\Server\htdocs\src index.html contains <base href="/ ...