diff --git a/sorting/counting.py b/sorting/counting.py new file mode 100644 index 0000000..9306b63 --- /dev/null +++ b/sorting/counting.py @@ -0,0 +1,19 @@ + +"""Python implementation of in-place counting sort algorithm""" + +def countingsort(array, maxval): + n = len(array) + m = maxval + 1 + # init with zeros + count = [0] * m + for a in array: + # count occurences + count[a] += 1 + i = 0 + for a in range(m): + # make 'count[a]' copies of 'a' + for c in range(count[a]): + array[i] = a + i += 1 + return array + diff --git a/tests.py b/tests.py index 270c350..ca41035 100644 --- a/tests.py +++ b/tests.py @@ -55,3 +55,13 @@ print "Bucket Sort incorrect" except: print "Bucketsort function errored or is incomplete" + +try: + from counting import countingsort + if(countingsort(list(nums), numpy.max(nums)) == sortedNums): + print "Counting Sort success!" + else: + print "Counting Sort incorrect." +except: + print "Countingsort function errored or is incomplete." +