|
1 |
| -# counting sort |
2 |
| - |
3 |
| -l = [] # l is the list |
4 |
| - |
5 |
| -n = int(input("Enter number of elements in the list: ")) |
6 |
| - |
7 |
| -highest = 0 |
8 |
| - |
9 |
| -for i in range(n): |
10 |
| - temp = int(input("Enter element" + str(i + 1) + ': ')) |
11 |
| - |
12 |
| - if temp > highest: |
13 |
| - highest = temp |
14 |
| - |
15 |
| - l += [temp] |
16 |
| - |
17 |
| - |
18 |
| -def counting_sort(l, h): |
19 |
| - bookkeeping = [0 for i in range(h + 1)] |
20 |
| - |
21 |
| - for i in l: |
22 |
| - bookkeeping[i] += 1 |
23 |
| - |
24 |
| - L = [] |
25 |
| - |
26 |
| - for i in range(len(bookkeeping)): |
27 |
| - |
28 |
| - if bookkeeping[i] > 0: |
29 |
| - |
30 |
| - for j in range(bookkeeping[i]): |
31 |
| - L += [i] |
32 |
| - |
33 |
| - return L |
34 |
| - |
35 |
| - |
36 |
| -print(counting_sort(l, highest)) |
| 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 |
| 7 | + |
| 8 | +def counting_sort(tlist, k, get_sortkey): |
| 9 | + """ Counting sort algo with sort in place. |
| 10 | + Args: |
| 11 | + tlist: target list to sort |
| 12 | + 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. |
| 14 | + map info to index of the count list. |
| 15 | + Adv: |
| 16 | + The count (after cum sum) will hold the actual position of the element in sorted order |
| 17 | + Using the above, |
| 18 | + |
| 19 | + """ |
| 20 | + |
| 21 | + # Create a count list and using the index to map to the integer in tlist. |
| 22 | + count_list = [0]*(k) |
| 23 | + |
| 24 | + # 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 |
| 27 | + |
| 28 | + # Modify count list such that each index of count list is the combined sum of the previous counts |
| 29 | + # 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] |
| 35 | + |
| 36 | + |
| 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 | + |
| 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) |
| 49 | + |
| 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