3

私はネットからの擬似コードから作られたこのpython Heapsort-Codeを持っています。

しかし、それは間違った結果をもたらします。

def heapSortUp(a):          
    heapifyUp(a, len(a))

    end = len(a)-1
    while end > 0:
        a[end], a[0] = a[0], a[end]
        end -= 1
        siftUp(a, 0, end)
    return a

def heapifyUp(a, count):
    end = 1

    while end < count:
        siftUp(a, 0, end)
        end += 1

def siftUp(a, start, end):
    child = end

    while child > start:
        parent = int(math.floor((child-1)/2))       # floor = abrunden

        if a[parent] < a[child]:
            a[parent], a[child] = a[child], a[parent]
            child = parent
        else:
            return

特にsiftUP版を使いたいです。

計算すると、次のprint heapSortUp([1,5,4,2,9,8,7]) ように返されます。[8, 7, 9, 2, 1, 4, 5, 7, 5]

4

2 に答える 2

1

ヒープ昇順ソートの場合、次のコードを使用できます。

def heapSort(a):
    count = len(a)
    heapify(a, count)

    end = count-1
    while end > 0:
        a[end], a[0] = a[0], a[end]
        end = end - 1
        siftDown(a, 0, end)


def heapify(a, count):
    start = math.floor((count - 1) / 2)

    while start >= 0:
        siftDown(a, start, count-1)
        start = start - 1

def siftDown(a, start, end):
    root = start

    while root * 2 + 1 <= end:
        child = root * 2 + 1
        swap = root
        if a[swap] < a[child]:
            swap = child
        if child+1 <= end and a[swap] < a[child+1]:
            swap = child + 1
        if swap != root:
            a[root], a[swap] = a[swap], a[root]
            root = swap
        else:
            return

または、次のコードを使用できます。

def heapSortDown(lst):
  for start in range(math.floor((len(lst)-2)/2), -1, -1):
    sift(lst, start, len(lst)-1)

  for end in range(len(lst)-1, 0, -1):
    lst[end], lst[0] = lst[0], lst[end]
    sift(lst, 0, end - 1)
  return lst

def sift(lst, start, end):
  root = start
  while True:
    child = root * 2 + 1
    if child > end: break
    if child + 1 <= end and lst[child] < lst[child + 1]:
      child += 1
    if lst[root] < lst[child]:
      lst[root], lst[child] = lst[child], lst[root]
      root = child
    else:
      break

および降順の場合:

def heapSortDown(lst):
  for start in range(math.floor((len(lst)-2)/2), -1, -1):
    sift(lst, start, len(lst)-1)

  for end in range(len(lst)-1, 0, -1):
    lst[end], lst[0] = lst[0], lst[end]
    sift(lst, 0, end - 1)
  return lst

def sift(lst, start, end):
  root = start
  while True:
    child = root * 2 + 1
    if child > end: break
    if child + 1 <= end and lst[child] > lst[child + 1]:
      child += 1
    if lst[root] > lst[child]:
      lst[root], lst[child] = lst[child], lst[root]
      root = child
    else:
      break
于 2013-05-16T06:15:21.080 に答える