Code Monkey home page Code Monkey logo

closest-search's Introduction

Closest-Search

Given an integer array sorted in ascending order and a certain integer; the task is to find the element of the array closest to this number.

'use strict'; const arr1 = [102, 201, 210, 420, 630, 1201, 2022, 2202, 20020, 20200, 200200, 1010010, 2020202, 2002002]; const arr2 = null; const num1 = 550; const num2 = 505500; /* O-notation = O(log(n)); */ function closestSearch(arr, num) { let part = 2; let size = arr.length; let root = Math.trunc(size/part); if (num > arr[size - 1]) { return arr[size - 1]; } else if (num < arr[0]) { return arr[0]; } else if (num < arr[root]) { while (true) { part += 1; root = Math.trunc(size/part); if (num > arr[root]) { break; }; }; while (true) { if (Math.abs(num - arr[root]) < Math.abs(arr[root + 1]- num)) { return arr[root]; break; } else { root += 1; continue; }; }; } else if (num > arr[root]) { while (true) { part += 1; root = Math.trunc((size/part) * (part - 1)); if (num < arr[root]) { break; }; }; while (true) { if (Math.abs(num - arr[root - 1]) > Math.abs(arr[root] - num)) { return arr[root]; break; } else { root -= 1; continue; }; }; }; }; console.log(closestSearch(arr1, num1)); console.log(closestSearch(arr1, num2));

closest-search's People

Contributors

junproger avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.