Skip to content

Commit 6125b7d

Browse files
committed
Issue(akshitagit#33): Sort in linear time. Added counting sort
1 parent ddc7d0f commit 6125b7d

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

Sorting_Searching/bucketSort.py

Whitespace-only changes.

Sorting_Searching/countSort.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
MAX = 1024
2+
3+
4+
# Linear time sorting algorithm
5+
def count_sort(arr):
6+
7+
count, sorted_arr = [0 for i in range(
8+
MAX + 1)], [0 for i in range(len(arr))]
9+
10+
# Make a hash
11+
for i in range(len(arr)):
12+
count[arr[i]] += 1
13+
14+
# count frequency
15+
for i in range(1, MAX + 1):
16+
count[i] += count[i - 1]
17+
18+
# a simple math to new position of element in sorted array
19+
for i in range(len(arr)):
20+
sorted_arr[count[arr[i]] - 1] = arr[i]
21+
count[arr[i]] -= 1
22+
23+
return sorted_arr
24+
25+
26+
# Stable algorithm for count sort
27+
def stable_count_sort(arr):
28+
29+
count, sorted_arr = [0 for i in range(
30+
MAX + 1)], [0 for i in range(len(arr))]
31+
32+
for i in range(len(arr)):
33+
count[arr[i]] += 1
34+
35+
for i in range(1, MAX + 1):
36+
count[i] += count[i - 1]
37+
38+
# traverse reverse for stability
39+
for i in range(len(arr) - 1, -1, -1):
40+
sorted_arr[count[arr[i]] - 1] = arr[i]
41+
count[arr[i]] -= 1
42+
43+
return sorted_arr
44+
45+
46+
# Driver Program to show the implementation
47+
lst = []
48+
size = int(input("Enter size of the list : "))
49+
for i in range(size):
50+
elements = int(input("Enter an element : "))
51+
lst.append(elements)
52+
print(stable_count_sort(lst))

0 commit comments

Comments
 (0)