Searching for the Magic Index using Binary Search

Currently working on mastering binary search and encountering difficulties while trying to use it to locate the "magic index" within an array, where the magic index is defined as A[i] == i.

While I have come across some Java implementations using recursion on this blog, I am exploring alternatives to recursion as it can be resource-intensive (and I want to test the suitability of binary search in this scenario).

Below is the code I have so far:

function magicIndex(arr) {
  var result = arr, mid;
  while (result.length > 1) {
    mid = Math.floor(result.length / 2);

    if (result[mid] === mid) {
      return arr.indexOf(result[mid]);
    } else if (mid > result[mid]) {
      result = result.slice(mid+1, result.length);
    } else {
      result = result.slice(0, mid);
    }
  }
  return arr.indexOf(result.pop());
}

The issue with the current algorithm is that it inconsistently slices the array during some test cases.

For instance, [-10, -3, 0, 2, 4, 8] yields 4, while [-10, 1, 0, 2, 5, 8] also produces 4.

Answer №1

The array you provided is not in sorted order, and for a successful implementation of a binary search, the array must be sorted.

Answer №2

As you continue to practice, it's beneficial for you to code on your own with some guidance.

Follow this algorithm (Make sure the input array is already sorted, or implement a sorting method):

  int arr[n];
  K ← 1; //search key
  l ← 0; r ← n - 1;
  while l ≤ r do
      m ← floor((l + r)/2)
      if K = arr[m]
          return m
      else if K < arr[m]
          r ← m − 1
      else
          l ← m + 1
  return −1

This will give you the index of your search key, or -1 if the key is not found.

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

"Is there a way for me to retrieve the response header within the .then function in AngularJS

How can I retrieve the response header from a GET request? I have a service function that returns a promise. In my Controller, I resolve the promise and in the .then function, I need to access the content type from the response header. I attempted to use ...

Creating a Vue2 modal within a v-for loop to display a dynamic

Recently, I've been working on implementing a vue2 modal following the instructions provided in the official Vue documentation at https://v2.vuejs.org/v2/examples/modal.html. The code snippet I have been using looks something like this: <tbody v-i ...

Generate time-dependent animations using circles

Hey there, I am trying to create an animation that involves drawing three circles and having one of them move from right to left. The circles should appear randomly in yellow, blue, or orange colors on the canvas at different intervals (3 seconds between ...

issue encountered when attempting to use string.replace with regex

When using a regex like this: I am attempting to replace "subdir" with a custom string using the string.replace method. However, when I use myStr.replace(/^.*\/\/.*\.net\/.*\/(.*)\/.*\z/, otherStr) The result is not as ...

Difficulty arises when transferring files in Node.js from one directory to another

Attempting to use node.js to transfer files from the currentFolder(root of project)/node_modules/mime/ to currentFolder(root of project)/files/, encountering an error: events.js:85 throw er; // Unhandled 'error' event ^ Error: ...

Error uploading file to Amazon S3: Node.js issue

I encounter a problem while trying to upload a file to Amazon S3. The provided code is: const s3 = require('s3'); const client = s3.createClient({ maxAsyncS3: 100, s3RetryCount: 3, s3RetryDelay: 30 ...

Using JavaScript and the Firefox browser, learn how to easily highlight an element with Selenium-WebDriver

I am struggling with creating a valid function to highlight specific elements on a webpage. As a beginner in coding, I suspect that the issue may either be related to my environment setup or a lack of knowledge about JavaScript/Selenium features. I am wri ...

Building a Div Tag Layout with CSS for Full Width and Left Position of 300px

Experiencing some trouble with styling a div element. My goal is to have the div start at left:300px and stretch across the entire width of the browser window. However, when I apply width:100%, the div extends beyond the boundaries of the browser screen. ...

Stop the infiltration of emotions into your style

Utilizing the JsonForms React Component to dynamically generate an HTML form in my web application. The framework I am using handles all view rendering on the server side. To integrate this component, I compiled a small react component by running npm run b ...

Error: The property 'rtl' is not defined and cannot be read

I'm currently in the process of developing a vuejs component library that utilizes vuetify 2.1.4 and attempting to import it into another application locally through npm link. However, I'm encountering numerous errors such as TypeError: Cannot ...

Divide a flat array into separate subarrays that group together values from consecutive keys in the original array

I used the array_diff function and got this array: Array ( [0] => world [1] => is [2] => a [3] => wonderfull [5] => in [6] => our ) The array has gaps between keys #3 and #5 (missing key #4). How can I split this ...

Trouble with ScrollView not scrolling on Nativescript-Vue

I am facing an issue with a scrollable view in my project. I have a list of items that should be scrollable, but for some reason it is not scrolling as expected. The structure involves a vertical stack layout wrapped in a scrollview, and inside the stackla ...

Having difficulties in Vue while attempting to access a particular row

I encountered an error message stating Uncaught TypeError: snapShotChnaged.forEach is not a function. My goal is to retrieve specific row data, which is why I am utilizing the doc method. retrieveSpecificDonation() { firestore .collection('d ...

Accessing the current route in a Vuex module using Vue.js

I've created a vuex store with namespaces that retrieves a specific store entry based on the current route parameter. import Router from '../../router/index' const options = { routeIdentifier: 'stepId' } export function fetchFr ...

Combining Mongoose OR conditions with ObjectIDs

After querying my Team schema, I am receiving an array of ids which I have confirmed is correct. The issue seems to lie in the fact that both home_team and away_team are ObjectIDs for the Team Schema within my OR statement. Team.find({ 'conferenc ...

Switching from React version 15.6.2 to 16 results in disruptions to the functionality of the web

Currently, I am encountering an issue where none of my index.js files are rendering. After using the react-scripts to build my web application in version 16.2.0, I receive an error stating that r.PropTypes is undefined when trying to access the localhost a ...

Only one JSON file is handled at a time, no duplicates are made

We start by utilizing the powerful D3 JavaScript library for initializing data documents, followed by creating a custom JavaScript script to handle data processing. An excerpt from the customized JavaScript script appears as follows: drawLegend(); ...

Determining where to implement the API display logic - on the server side or

Currently, I am in the process of restructuring an API that deals with user profiles stored in one table and profile images in another. The current setup involves querying the profiles table first and then looping through the images table to gather the ass ...

HTML5 video player with secondary playlist

Looking for a videoplayer setup where there are two playlists, but only one can play at a time. When choosing a video from the first list initially, nothing happens. However, after selecting a video from the second list, the first list starts working. HTM ...

Rails assets folder is not directed to the specified directory in the layout file

I have a dilemma in the application layout where I'm referencing assets (js, css, and img) in the public/assets/... directory. For example: <link href='assets/images/meta_icons/apple-touch-icon-144x144.png' rel='apple-touch-icon-pre ...