Exemplo n.º 1
0
def select_sort(tList):
    if not tList:
        return
    for i in range(1, len(tList)):
        min = i-1
        for j in range(i, len(tList)):
            if tList[j] < tList[min]:
                min = j
        swap(tList, i-1, min)
Exemplo n.º 2
0
 def extract_max(self):
     """ return and remove the top element """
     if self.size == 0:
         return None
     max = self._list[0]
     swap(self._list, 0, self.size-1)
     self.size = self.size-1
     if self.size > 1:
         self._down_heapify(0)
     return max
Exemplo n.º 3
0
 def _down_heapify(self, index):
     left = index*2+1
     right = left+1
     max = index
     if left<self.size and self._is_bigger(left, max):
         max = left
     if right<self.size and self._is_bigger(right, max):
         max = right 
     if max != index:
         swap(self._list, max, index)
         self._down_heapify(max)
Exemplo n.º 4
0
def bubble_sort(tList):
    if not tList:
        return
    for i in range(len(tList)-1, 0, -1):
        exchange = False
        for j in range(1, i+1):
            if tList[j] < tList[j-1]:
                swap(tList, j, j-1)
                exchange = True
        if not exchange:
            break
Exemplo n.º 5
0
def perm(tList, cbk, start=None, end=None):
    """
        generate the permutation of tList, for each list in the permutation result,
        call cbk(list)
        start is the first index, None means 0
        end is the last index, None means len(tList)-1
    """
    if start is None:
        start = 0
    if end is None:
        end = len(tList)-1
    if start>=end:
        cbk(tList)
        return
    for i in range(start, end+1):
        swap(tList, start, i)
        perm(tList, cbk, start+1, end)
        swap(tList, start, i)
Exemplo n.º 6
0
def partition(tList, start, end):
    p = random.randint(start, end)
    mValue = tList[p]
    swap(tList, start, p)
    i,j = start+1,end
    while i<=j:
        while i<=j and tList[i]<=mValue:
            i = i+1
        while i<=j and tList[j]>=mValue:
            j = j-1
        if i<j:
            swap(tList, i, j)
            i = i+1
            j = j-1
    p = i-1
    swap(tList, start, p)
    return p
Exemplo n.º 7
0
 def exchange(i, j):
     swap(tList, i, j)
     swap(flags, i, j)
Exemplo n.º 8
0
def sort(tList):
    for j in range(len(tList)-1, 0, -1):
        for i in range(1, j+1):
            if tList[i] < tList[i-1]:
                swap(tList, i, i-1)
Exemplo n.º 9
0
 def _top_heapify(self, index):
     parent = (index-1)/2
     if parent>=0 and self._is_bigger(index, parent):
         swap(self._list, index, parent)
         self._top_heapify(parent)