Python小程序——线性时间排序

 1 '''最好让k的值与list的元素数量n差不多,如果是n的幂的话就不合适了'''
 2 
 3 
 4 def init_part(k,out_list):
 5     #k is the max int of out_list.Value in out_list is larger than >= 0.
 6     Assist_list = []
 7     Assist_list_2 = []
 8     for i in range(0,k+1,1): #consider the value 0.#initial the Assist_list and 2
 9         Assist_list.append(0)
10         Assist_list_2.append(0)
11 
12     for i in range(0,len(out_list),1):
13     #put the value in the Assist_list
14         Assist_list[out_list[i]] +=1
15 
16     res=0
17     for i in range(0,k+1,1):
18         #get the final assit list. 将Assist_list里面的每个位的数量转化为位置数。
19         Assist_list_2[i] = res + Assist_list[i]
20         res = res + Assist_list[i]
21     # print('Assit list is ',Assist_list_2)
22     return Assist_list_2
23 
24 def sort_func(list1,list2):
25     import copy
26     list3 = copy.deepcopy(list1)
27     # print('list3 is ',list3)
28     end_num = len(list1)
29     for i in range(end_num-1,-1,-1):
30         tmp_num = list1[i]
31         sort_num = list2[tmp_num]-1
32         list2[tmp_num] -= 1
33         list3[sort_num] = list1[i]
34         # print('list3 end is ', list3)
35         # print('list2 end is', list2)
36     return list3
37 
38 def liner_time_sort(target_list):
39     max_value = max(target_list)
40     temp_list = init_part(max_value,target_list)
41     final_list= sort_func(target_list,temp_list)
42     print('final list is ',final_list)
43     return final_list
44 
45 if __name__=="__main__":
46 
47     a= [4,1,2,4,3,7,2,1,2,3,4,6,3,1,1,1,1,12,1,1,1,1111,11111,10]
48     b = [32,34,21,45,666,213,41,23,78,64,36,83,18,41,332,6466,432]
49     import time
50     # t1=time.time()
51     # Final_list = liner_time_sort(b)
52     # t2 = time.time()
53     # print('total time is ',t2-t1)
54     t1 = time.time()
55     Final_list = liner_time_sort(a)
56     t2 = time.time()
57     print('total time is ', t2 - t1)

 

posted @ 2018-04-10 17:45  Ian_learning  阅读(553)  评论(0编辑  收藏  举报