Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8acca72

Browse files
counting sort
1 parent 4092ff4 commit 8acca72

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# COUNTING SORT
2+
3+
- Counting sort is a sorting technique based on keys between a specific range.
4+
- It works by counting the number of objects having distinct key values (kind of hashing).
5+
- Then doing some arithmetic to calculate the position of each object in the output sequence.
6+
7+
```python
8+
def counting_sort(array, maxval):
9+
n = len(array)
10+
m = maxval + 1
11+
count = [0] * m # init with zeros
12+
for a in array:
13+
count[a] += 1 # count occurences
14+
i = 0
15+
for a in range(m): # emit
16+
for c in range(count[a]): # emit "count[a]" copies of "a"
17+
array[i] = a
18+
i += 1
19+
return array
20+
21+
22+
arr = [1,4,7,2,1,3,2,1,4,2,3,2,1]
23+
print("Output: ", counting_sort(arr, 7))
24+
```
25+
output:
26+
```
27+
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 7]
28+
```
29+
30+
<img src="https://cdn.programiz.com/sites/tutorial2program/files/Counting-sort-4_1.png" />
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
def counting_sort(array, maxval):
2+
n = len(array)
3+
m = maxval + 1
4+
count = [0] * m # init with zeros
5+
for a in array:
6+
count[a] += 1 # count occurences
7+
i = 0
8+
for a in range(m): # emit
9+
for c in range(count[a]): # emit "count[a]" copies of "a"
10+
array[i] = a
11+
i += 1
12+
return array
13+
14+
15+
arr = [1,4,7,2,1,3,2,1,4,2,3,2,1]
16+
print("Output: ", counting_sort(arr, 7))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /