rechdicho.py

Created by pascal-chauvin

Created on June 25, 2019

862 Bytes

Effectue une recherche dichotomique de x dans le tableau T.


#!/usr/bin/env python3

# fichier : rech.py
#  auteur : Pascal CHAUVIN
#    date : 2019-06-25

"""
Recherche (dichotomique) de la valeur x dans le tableau T :

T est un tableau
x est un nombre

La fonction rend le rang de x dans le tableau, si x est present 
dans le tableau, et la valeur "None" (aucun) sinon.
"""

def recherche(T, x):
  i = 0
  j = len(T) - 1
  m = None

  p = 0

  while (i <= j) and (m is None):
    p += 1
    print("p={}, i={}, j={}, j-i={}".format(p, i, j, j-i))
    k = (i + j) // 2
    if T[k] == x:
      m = k
    else:
      if T[k] < x:
        i = k + 1
      else:
        j = k - 1
  return m



import random

T = [random.randint(0, 100) for _ in range(20)]
#T = sorted([random.randint(0, 100) for _ in range(20)])
#T = []
x = random.randint(0, 100)

print(T)
print(x)
print("indice={}".format(recherche(T, x)))

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.