Quicksort

lecture notes


In [1]:
import pandas
from bokeh.io import push_notebook, show, output_notebook
from bokeh.charts import Bar
from bokeh.plotting import figure
from bokeh.plotting import reset_output

import random
import time

In [2]:
data = [random.randint(0,100) for c in range(80)]

In [3]:
def quick_sort(items, left, right, handle=None):
    i = left
    j = right
    
    x = items[(left+right) // 2]
    while i <=j:
        while items[i] < x and i < right:
            i += 1
        while x < items[j] and j > left:
            j -= 1
        
        if i <= j:
            y = items[i]
            items[i] = items[j]
            items[j] = y
            i += 1
            j -= 1
            if handle is not None:
                push_notebook(handle=handle)
                time.sleep(0.01)
    
    if left < j:
        quick_sort(items, left, j, handle)

    if i < right:
        quick_sort(items, i, right, handle)


def q_sort(data):
        
    temp = data[:]

    output_notebook()

    p = figure(plot_width=400, plot_height=400, title='quick sort')
    vb = p.vbar(x=[c for c in range(len(temp))], width=0.5, bottom=0, top=temp, color="firebrick")
    init = p.vbar(x=[c for c in range(len(data))], width=0.5, bottom=0, top=data, color="gray", alpha=0.75)
    
    t = show(p, notebook_handle=True)

    quick_sort(temp, 0, len(temp)-1, t)
    
    reset_output()
    
    return temp

In [6]:
items = q_sort(data)


Loading BokehJS ...

In [ ]: