首页 > 解决方案 > 合并排序算法排序时间和交换计数

问题描述

我创建了一个程序,其中为列表/数组随机生成数字。在这个列表中,我需要计算排序列表需要多长时间以及排序需要的交换次数。

以下是我的代码。该代码解决了列表没有任何问题,但时间和交换计数器无法正常工作,它只是给了我0,1,1,1,2,1,1,0,2,4类似的结果。

添加到count以及在start.time and end.time

import random
import time
#X--------------------------------------------------------------------------------------------------------------------------------------------------------------------

# Random Number Generator
def random_generator():
    randomNumber = random.randint(0, 1000)
    return randomNumber
#X--------------------------------------------------------------------------------------------------------------------------------------------------------------------

def arraygenerator():
    arr = []
    for draw in range(15):
        randomNumber = random_generator()
        arr.append(randomNumber)
    print ("Unsorted Array is : ", arr)
    return arr

def counter(count):
    return count



def merge(S1, S2, S):
  start = time.time()
  count = 0
  
  i = j = 0
  while i + j < len(S):
    if j == len(S2) or (i < len(S1) and S1[i] < S2[j]):
      S[i+j] = S1[i]      
      i += 1
      count +=1
      
    else:
      S[i+j] = S2[j]      
      j += 1
  end = time.time()
  print(f"Runtime of the program is {end - start}")
  print(counter(count)) 
def merge_sort(S):
  
  
  n = len(S)
  if n < 2:
    return               
  
  mid = n // 2
  S1 = S[0:mid]          
  S2 = S[mid:n]           
  
  merge_sort(S1)        
  merge_sort(S2)          
  merge(S1, S2, S)        

def main():
  print('The list S1 to be sorted.....')
  s1 = arraygenerator()
  merge_sort(s1)

  print('The sorted list is ', s1)

  
main()

当我运行代码时,我的输出是

The list S1 to be sorted.....
Unsorted Array is :  [697, 126, 983, 400, 400, 583, 166, 343, 517, 819, 265, 193, 362, 993, 876]
Runtime of the program is 0.0
1
Runtime of the program is 0.0
1
Runtime of the program is 0.0
1
Runtime of the program is 0.0
1
Runtime of the program is 0.0
2
Runtime of the program is 0.0
3
Runtime of the program is 0.0
1
Runtime of the program is 0.0
1
Runtime of the program is 0.0
2
Runtime of the program is 0.0
1
Runtime of the program is 0.0
1
Runtime of the program is 0.0
2
Runtime of the program is 0.0
4
Runtime of the program is 0.0
7
The sorted list is  [126, 166, 193, 265, 343, 362, 400, 400, 517, 583, 697, 819, 876, 983, 993]

标签: pythonarrayssortingmergesort

解决方案


推荐阅读