如何计算快速排序中的掉期? (蟒蛇)

时间:2014-06-07 00:50:10

标签: python algorithm list counter quicksort

你好我有这个代码而且我不知道如何计算它做了多少交换:(

def quicksort(lista,izq,der):
i = izq
j = der
pivote = lista[(izq + der)//2]

while i <= j:
    while lista[i] < pivote:
        i += 1
    while pivote < lista[j]:
        j -= 1
    if i <= j:
        aux = lista[i]
        lista[i] = lista[j]
        lista[j] = aux
        i += 1
        j -= 1

if izq < j:
    quicksort(lista, izq, j);
if i < der:
    quicksort(lista, i, der);

那么我在哪里可以放一个柜台,告诉我它有多少交换呢? 编辑:我需要该函数返回该数字以及它的比较数。

2 个答案:

答案 0 :(得分:1)

def quicksort(lista,izq,der):
   i = izq
   j = der
   pivote = lista[(izq + der)//2]

   swap_count = 0
   while i <= j:
      while lista[i] < pivote:
         i += 1
      while pivote < lista[j]:
         j -= 1
      if i <= j:
         aux = lista[i]
         lista[i] = lista[j]
         lista[j] = aux
         swap_count += 1
         i += 1
         j -= 1

   if izq < j:
      swap_count += quicksort(lista, izq, j)
   if i < der:
      swap_count += quicksort(lista, i, der)

   return swap_count

答案 1 :(得分:0)

如果我理解你的话,我会做什么。

def quicksort(lista,izq,der):
  i = izq
  j = der
  swap_count = 0
  compare_count = 0
  pivote = lista[(izq + der)//2]

  while i <= j:
    while lista[i] < pivote:
      i += 1
    while pivote < lista[j]:
      j -= 1
    if i <= j:
      aux = lista[i]
      lista[i] = lista[j]
      lista[j] = aux
      swap_count += 1
      i += 1
      j -= 1
    compare_count += 1

  if izq < j:
    other_swap, other_compare = quicksort(lista, izq, j)
    swap_count += other_swap
    compare_count += other_compare
  if i < der:
    other_swap, other_compare = quicksort(lista, i, der)
    swap_count += other_swap
    compare_count += other_compare    

  return (swap_count, compare_count)

这样,您可以在交换时添加交换和递归调用的比较。

相关问题