无法在Counting Sort中打印出一个元素

时间:2018-02-27 18:28:38

标签: python arrays sorting

我尝试使用附加数组编写Counting Sort算法,但不知何故,随机生成的数组中的1个元素不会打印出来。

public class Circle implements Collidable{

   public boolean checkCollision(Collidable target){
      if(target instanceof Cirlce){
         //Algorithm for circle-circle collision
      }else if(target instanceof Line){
         //Algorithm for circle-line collision
         //...
      }else{
         return false;
      }
   }
}

2 个答案:

答案 0 :(得分:0)

这应该这样做:

import random
import time
start_time = time.clock()
N = random.randint(3,12)                                     
list1 = []*N
for i in range (N):                                       
    list1.insert(random.randint(1,100),random.randint(1,100)) 
print("Input array: ",list1)                                                  

B = [0]*(N+1)
for i in range(N):
    k = 1
    for j in range(N):
         if (list1[j]<list1[i]) or ((list1[j]==list1[i]) and (j<i)):
             k = k+1
    B[k]=list1[i]
for i in range(N):
    list1[i]=B[i]


print("Sorted array: ",B)
print("Amount of numbers in array: ",N)
print("Code is finished within",time.clock()-start_time, "seconds")


Input array:  [47, 28, 93, 92, 74, 13]
Sorted array:  [0, 13, 28, 47, 74, 92, 93]

在python中,事情是零索引的,所以说range(1,N+1)range(1,N)跳过索引0

答案 1 :(得分:0)

更改您的代码
B = [0]*(N+1)
    for i in range(1,N):
        k = 1
        for j in range(1,N):

B = [0]*(N)
for i in range(0,N):
    k = 0
    for j in range(0,N):

因为列表是零索引的。 希望这对你有所帮助。