Skip to content

Instantly share code, notes, and snippets.

@tsavo-at-pieces
Created June 9, 2023 00:07
Show Gist options
  • Save tsavo-at-pieces/d7b84ed081705044e130be4291096914 to your computer and use it in GitHub Desktop.
Save tsavo-at-pieces/d7b84ed081705044e130be4291096914 to your computer and use it in GitHub Desktop.
This code searches for a given value in a list and returns the index of each element if it is less than or equal to another one.

Searching for End of List

Preview:
int binarySearch(List<int> sortedList, int targetValue) {
  // Define the start and end indices for the search
  int startIndex = 0;
  int endIndex = sortedList.length - 1;

  // Continue searching while the start index is less than or equal to the end index
  while (startIndex <= endIndex) {
    // Calculate the middle index of the current search range
    int middleIndex = startIndex + ((endIndex - startIndex) ~/ 2);

    // Check if the target value is at the middle index
    if (sortedList[middleIndex] == targetValue) {
      // If it is, return the middle index
      return middleIndex;
    } else if (sortedList[middleIndex] < targetValue) {
      // If the target value is greater than the value at the middle index,
      // update the start index to be one position after the middle index
      startIndex = middleIndex + 1;
    } else {
      // If the target value is less than the value at the middle index,
      // update the end index to be one position before the middle index
      endIndex = middleIndex - 1;
    }
  }

  // If the target value is not found after searching the entire list, return -1
  return -1;
}
Associated Context
Type Code Snippet ( .dart )
Associated Tags Data Structures JavaScript SDK Target Value Middle Index Search List End Index Searching Elements Start Index
💡 Smart Description This code searches for a given value in a list and returns the index of each element if it is less than or equal to another one.
🔎 Suggested Searches Find middle index of a list
Search for target value in an array using JavaScript
How to find the start and end indices sortedList
Finding which elements are not equal to another range?
Determine how to search for this element within its length
Related Links No Related Links
Related People Tsavo Knott
Sensitive Information No Sensitive Information Detected
Shareable Link https://tsavo.pieces.cloud/?p=f9a74fa00e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment