Recent Changes - Search:

Oktatás

* Programozás 2
  + feladatsor
  + C feladatsor
  + Python feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

* Adator. prog.
  + feladatsor
  + quick link

Teaching

* Prog. for Data Sci.
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2025/26/1
* archívum


Linkek

* kalendárium
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Scala


[ edit | logout ]
[ sandbox | passwd ]

Binary search

See also SortedRange.

(1) binary search
import bisect


# see also https://realpython.com/binary-search-python/
def binary_search(elements, value) -> int:
    idx = bisect.bisect_left(elements, value)
    if idx < len(elements) and elements[idx] == value:
        return idx
    # else
    return -1  # not found


def main():
    numbers = [1, 3, 4, 7, 9]  # sorted

    print(binary_search(numbers, 7))  # 3 (index position)

    print(binary_search(numbers, 5))  # -1 (not found)
import std.stdio;

import std.range; // assumeSorted()
import std.algorithm;

void main()
{
    int[] numbers = [1, 3, 4, 7, 9]; // sorted
    // let D know that it's sorted:
    auto r = assumeSorted(numbers); // returns a SortedRange

    writeln(r.contains(7)); // true
    writeln(r.contains(5)); // false

    writeln("---");

    int[] values = [8, 5, 1, 3]; // NOT sorted
    auto r2 = values.sort(); // sort() returns a SortedRange

    writeln(r2.contains(5)); // true
    writeln(r2.contains(9)); // false
}

Notes:

  • In Python, bisect_left() returns the would-be position of a non-existing element. For instance, if you're looking for 5 in [1, 4, 7], it returns the position between 4 and 7. That's why we need the extra if statement after calling bisect_left().
  • In D, sort() sorts the list in-place AND returns a SortedRange.
Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2025 August 24, 14:46