|
| 1 | +def counting_sort(arr): |
| 2 | + """ |
| 3 | + Counting_sort |
| 4 | + Sorting a array which has no element greater than k |
| 5 | + Creating a new temp_arr,where temp_arr[i] contain the number of |
| 6 | + element less than or equal to i in the arr |
| 7 | + Then placing the number i into a correct position in the result_arr |
| 8 | + return the result_arr |
| 9 | + Complexity: 0(n) |
| 10 | + """ |
| 11 | + |
| 12 | + m = min(arr) |
| 13 | + #in case there are negative elements, change the array to all positive element |
| 14 | + different = 0 |
| 15 | + if m < 0: |
| 16 | + #save the change, so that we can convert the array back to all positive number |
| 17 | + different = -m |
| 18 | + for i in range (len(arr)): |
| 19 | + arr[i]+= -m |
| 20 | + k = max(arr) |
| 21 | + temp_arr = [0]*(k+1) |
| 22 | + for i in range(0,len(arr)): |
| 23 | + temp_arr[arr[i]] = temp_arr[arr[i]]+1 |
| 24 | + #temp_array[i] contain the times the number i appear in arr |
| 25 | + |
| 26 | + for i in range(1, k+1): |
| 27 | + temp_arr[i] = temp_arr[i] + temp_arr[i-1] |
| 28 | + #temp_array[i] contain the number of element less than or equal i in arr |
| 29 | + |
| 30 | + result_arr = [0]*len(arr) |
| 31 | + #creating a result_arr an put the element in a correct positon |
| 32 | + for i in range(len(arr)-1,-1,-1): |
| 33 | + result_arr[temp_arr[arr[i]]-1] = arr[i]-different |
| 34 | + temp_arr[arr[i]] = temp_arr[arr[i]]-1 |
| 35 | + |
| 36 | + return result_arr |
| 37 | + |
| 38 | +if __name__ == "__main__": |
| 39 | + positive_array = [1,2,3,4,9,1,2,8,3,5,7,0,9,8,1,7,4,5] |
| 40 | + negative_array = [-5,-6,-2,-3,-4,-5,0,-9,-2,-3,-8,-4] |
| 41 | + x = counting_sort(positive_array) |
| 42 | + y = counting_sort(negative_array) |
| 43 | + print(x) |
| 44 | + print(y) |
| 45 | + |
| 46 | + |
0 commit comments