diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index 1b8365cc..2500e211 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -32,6 +32,7 @@ ## Sorting - [Bubble Sort](sorting/bubble_sort.py) - [Comb Sort](sorting/comb_sort.py) +- [Count Sort](sorting/count-sort.py) - [Insertion Sort](sorting/insertion_sort.py) - [Quicksort](sorting/quicksort.py) - [Selection Sort](sorting/selection_sort.py) diff --git a/algorithms/Python/sorting/count-sort.py b/algorithms/Python/sorting/count-sort.py new file mode 100644 index 00000000..228583b8 --- /dev/null +++ b/algorithms/Python/sorting/count-sort.py @@ -0,0 +1,28 @@ +#Code in python for count sort +def count_sort(a): + max_element = int(max(a)) + min_element = int(min(a)) + range_of_elements = max_element - min_element + 1 + # Create a count array to store count of individual + # elements and initialize count array as 0 + c= [0 for _ in range(range_of_elements)] + o= [0 for _ in range(len(a))] + for i in range(0, len(a)): + c[a[i]-min_element] += 1 + for i in range(1, len(c)): + c[i] += c[i-1] + for i in range(len(a)-1, -1, -1): + o[c[a[i] - min_element] - 1] = a[i] + c[a[i] - min_element] -= 1 + for i in range(0, len(a)): + a[i] = o[i] + + return a +a=[-1,-2,6,5,10] +ans = count_sort(a) +print("Sorted array is ") +print(ans) + +#TIME COMPLEXITY +#O(n+k) where n is the number of elements in input array and k is the range of input +