Skip to content

Commit 2e11640

Browse files
authored
Add files via upload
2025/7/18
1 parent 472bcac commit 2e11640

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

Sorting/Counting_sort.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
def counting_sort(arr):
2+
max_val=max(arr)#find the maximum value in the array
3+
count=[0]*(max_val+1)#create a count array with size of max_val+1
4+
5+
while len(arr)>0:#count the occurrences of each number
6+
num=arr.pop(0)#pop the first element
7+
count[num]+=1#increment the count for that number
8+
#reconstruct the sorted array
9+
for i in range(len(count)):
10+
while count[i]>0: #while there are occurrences of the number
11+
arr.append(i) #append the number to the sorted array
12+
count[i]-=1 #decrement the count for that number
13+
14+
return arr
15+
#main function to test the counting_sort function
16+
if __name__=="__main__":
17+
arr=[5,2,9,1,7,6,17,3,4,8,10]
18+
print(f"Original array:{arr}")
19+
sorted_arr=counting_sort(arr)
20+
print(f"Sorted array(counting_sort):{sorted_arr}")

0 commit comments

Comments
 (0)