[Python] Quicksort in python - alternative implementation, with median of 3

Discussão em 'Python' iniciado por Stack, Agosto 1, 2025.

  1. Stack

    Stack Membro Participativo

    Unsure why my code seems to be going on forever? Trying to implement the code from lectures....

    def median(a, a_i, b, b_i, c, c_i):
    if (a <= b and c <= a) or (a <= c and b <= a):
    return (a, a_i)
    elif (b <= a and c <= b) or (b <= c and a <= b):
    return (b, b_i)
    else:
    return (c, c_i)

    def partition(a, lo, hi):
    p = a[lo]
    if hi - lo + 1 >= 3:
    x = [random.randint(lo, hi) for _ in range(3)]
    (p, p_i) = median(a[x[0]], x[0], a[x[1]], x[1], a[x[2]], x[2])
    a[lo], a[p_i] = a[p_i], a[lo]
    i = lo
    j = hi + 1
    while True:
    while i < hi and a[i + 1] < p:
    i += 1
    while j > lo and a[j - 1] > p:
    j -= 1
    if i >= j:
    break
    a, a[j] = a[j], a

    a[lo], a[j] = a[j], a[lo]
    return j

    def sort(a, lo, hi):
    if hi <= lo:
    return
    j = partition(a, lo, hi)
    sort(a, lo, j - 1)
    sort(a, j + 1, hi)

    def q_sort(a):
    sort(a, 0, len(a) - 1)


    Tried changing while loop conditions, partition methods, etc... The code seems to have entered an infinite loop and I'm struggling to figure out why

    Continue reading...

Compartilhe esta Página