Search code examples
javascriptsortingbinary-search

How does javascript do the comparison?


I have an object array that gets new values every time a new user is created. I need to do some search based on the person name and then do some operations with it and I implemented a binary search and in my code that I found in the internet but theres something thats bothering me with the search code.

The object looks as follows:

person = {
      name: name,
      password: password,
      cartItems: '',
      cartPrice: 0
}

then I push it to an array.

and the binary search code looks as follows:

searchValues(users, value) {
    var startIndex = 0,
        stopIndex = users.length,
        middle = Math.floor((stopIndex + startIndex) / 2);

    while(users[middle].name != value && startIndex < stopIndex){
      //adjust search area
      if (value < users[middle].name) {
          stopIndex = middle - 1;
      } else if (value > users[middle].name) {
          startIndex = middle + 1;
      }
      //recalculate middle
      middle = Math.floor((stopIndex + startIndex) / 2);
    }

    return (users[middle].name != value) ? -1 : middle;
}

My questions is: How does JavaScript do the comparison between string values, does it convert to ascii? I can understand the code if it was applied to numbers but I'm a bit confused when it comes to strings.

Thank you in advance for anyone willing to help

EDIT: I forgot to mention that i've sorted my array before hand.


Solution

  • The algorithm to compare two strings is simple:

    1. Compare the first character of both strings.
    2. If the first character from the first string is greater (or less) than the other string’s, then the first string is greater (or less) than the second. We’re done.
    3. Otherwise, if both strings’ first characters are the same, compare the second characters the same way.
    4. Repeat until the end of either string.
    5. If both strings end at the same length, then they are equal. Otherwise, the longer string is greater. reference find more detail here