1
1
#python program for counting sort (updated)
2
- #import some libraries
3
- import random , math
4
- def get_sortkey (n ):
5
- # Define the method to retrieve the key
6
- return n
2
+ n = int (input ("please give the number of elements\n " ))
3
+ tlist = list ()
4
+ print ("okey now plase give the elemets" )
5
+ for i in range (n ):
6
+ tlist .append (int (input ("\n " )))
7
+ k = max (tlist )
8
+ n = len (tlist )
7
9
8
- def counting_sort (tlist , k , get_sortkey ):
10
+
11
+ def counting_sort (tlist , k , n ):
12
+
9
13
""" Counting sort algo with sort in place.
10
14
Args:
11
15
tlist: target list to sort
12
16
k: max value assume known before hand
13
- get_sortkey: function to retrieve the key that is apply to elements of tlist to be used in the count list index.
17
+ n: the length of the given list
14
18
map info to index of the count list.
15
19
Adv:
16
20
The count (after cum sum) will hold the actual position of the element in sorted order
@@ -19,35 +23,24 @@ def counting_sort(tlist, k, get_sortkey):
19
23
"""
20
24
21
25
# Create a count list and using the index to map to the integer in tlist.
22
- count_list = [0 ]* (k )
26
+ count_list = [0 ]* (k + 1 )
23
27
24
28
# iterate the tgt_list to put into count list
25
- for n in tlist :
26
- count_list [get_sortkey ( n )] = count_list [ get_sortkey ( n )] + 1
29
+ for i in range ( 0 , n ) :
30
+ count_list [tlist [ i ]] += 1
27
31
28
32
# Modify count list such that each index of count list is the combined sum of the previous counts
29
33
# each index indicate the actual position (or sequence) in the output sequence.
30
- for i in range (k ):
31
- if i == 0 :
32
- count_list [i ] = count_list [i ]
33
- else :
34
- count_list [i ] += count_list [i - 1 ]
34
+ for i in range (1 ,k + 1 ):
35
+ count_list [i ] = count_list [i ] + count_list [i - 1 ]
35
36
37
+ flist = [0 ]* (n )
38
+ for i in range (n - 1 ,- 1 ,- 1 ):
39
+ count_list [tlist [i ]] = count_list [tlist [i ]]- 1
40
+ flist [count_list [tlist [i ]]]= (tlist [i ])
36
41
37
- output = [None ]* len (tlist )
38
- for i in range (len (tlist )- 1 , - 1 , - 1 ):
39
- sortkey = get_sortkey (tlist [i ])
40
- output [count_list [sortkey ]- 1 ] = tlist [i ]
41
- count_list [sortkey ] -= 1
42
+ return flist
42
43
43
- return output
44
-
45
- #----- take list from user-----------
46
- li_st = [int (x ) for x in input ().split ()]
47
- print ("Unsorted List" )
48
- print (li_st )
44
+ flist = counting_sort (tlist , k , n )
45
+ print (flist )
49
46
50
- ##------working on our algo-----------
51
- print ("\n Sorted list using basic counting sort" )
52
- output = counting_sort (li_st , max (li_st ) + 1 , get_sortkey )
53
- print (output )
0 commit comments