Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

二分查找 #2

Open
RicoLiu opened this issue Feb 9, 2018 · 0 comments
Open

二分查找 #2

RicoLiu opened this issue Feb 9, 2018 · 0 comments

Comments

@RicoLiu
Copy link
Owner

RicoLiu commented Feb 9, 2018

         /**
         * 二分查找法(有序数组)
         * 
         * 时间复杂度: O(log N).
         *
         * @param {Array} array .
         * @param {Number} value.
         * @returns {Number} Index of the element or -1 if not found.
         */

         function binarySearch(array, value) {
            var middle = Math.floor(array.length / 2);
            var left = 0;
            var right = array.length;
            while (right >= left) {
              var middleValue = array[middle];
              if (middleValue === value) {
                  return middle;
              } else if (middleValue > value) {
                  right = middle - 1;
              } else {
                  left = middle + 1;
              } 
              middle = Math.floor((left + right) / 2);
            }
            return -1;
        }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant