Skip to content

Commit e1c4e6a

Browse files
author
kostasdedesar
committed
Simplified code improved input on Counting-Sort.py
1 parent a19a798 commit e1c4e6a

File tree

1 file changed

+23
-30
lines changed

1 file changed

+23
-30
lines changed

Counting-sort.py

+23-30
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
11
#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)
79

8-
def counting_sort(tlist, k, get_sortkey):
10+
11+
def counting_sort(tlist, k, n):
12+
913
""" Counting sort algo with sort in place.
1014
Args:
1115
tlist: target list to sort
1216
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
1418
map info to index of the count list.
1519
Adv:
1620
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):
1923
"""
2024

2125
# 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)
2327

2428
# 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
2731

2832
# Modify count list such that each index of count list is the combined sum of the previous counts
2933
# 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]
3536

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])
3641

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
4243

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)
4946

50-
##------working on our algo-----------
51-
print("\nSorted list using basic counting sort")
52-
output = counting_sort(li_st, max(li_st) +1, get_sortkey)
53-
print(output)

0 commit comments

Comments
 (0)