{"id":25188,"date":"2017-10-15T14:49:54","date_gmt":"2017-10-15T09:19:54","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25188"},"modified":"2017-10-15T14:49:54","modified_gmt":"2017-10-15T09:19:54","slug":"counting-sort","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/counting-sort\/","title":{"rendered":"Counting Sort"},"content":{"rendered":"<p>Counting Sort is a sorting technique based on keys between a specific range.<span id=\"more-115936\"><\/span> It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence.<\/p>\n<p>Let us understand it with the help of an example.<\/p>\n<pre>For simplicity, consider the data in the range 0 to 9. \r\nInput data: 1, 4, 1, 2, 7, 5, 2\r\n  1) Take a count array to store the count of each unique object.\r\n  Index:     0  1  2  3  4  5  6  7  8  9\r\n  Count:     0  2  2  0   1  1  0  1  0  0\r\n\r\n  2) Modify the count array such that each element at each index \r\n  stores the sum of previous counts. \r\n  Index:     0  1  2  3  4  5  6  7  8  9\r\n  Count:     0  2  4  4  5  6  6  7  7  7\r\n\r\nThe modified count array indicates the position of each object in \r\nthe output sequence.\r\n \r\n  3) Output each object from the input sequence followed by \r\n  decreasing its count by 1.\r\n  Process the input data: 1, 4, 1, 2, 7, 5, 2. Position of 1 is 2.\r\n  Put data 1 at index 2 in output. Decrease count by 1 to place \r\n  next data 1 at an index 1 smaller than this index.\r\n<\/pre>\n[ad type=&#8221;banner&#8221;]\n<p>Following is C implementation of counting sort.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">c<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ C Program for counting sort<br\/>#include &lt;stdio.h&gt;<br\/>#include &lt;string.h&gt;<br\/>#define RANGE 255<br\/> <br\/>\/\/ The main function that sort the given string arr[] in<br\/>\/\/ alphabatical order<br\/>void countSort(char arr[])<br\/>{<br\/>    \/\/ The output character array that will have sorted arr<br\/>    char output[strlen(arr)];<br\/> <br\/>    \/\/ Create a count array to store count of inidividul<br\/>    \/\/ characters and initialize count array as 0<br\/>    int count[RANGE + 1], i;<br\/>    memset(count, 0, sizeof(count));<br\/> <br\/>    \/\/ Store count of each character<br\/>    for(i = 0; arr[i]; ++i)<br\/>        ++count[arr[i]];<br\/> <br\/>    \/\/ Change count[i] so that count[i] now contains actual<br\/>    \/\/ position of this character in output array<br\/>    for (i = 1; i &lt;= RANGE; ++i)<br\/>        count[i] += count[i-1];<br\/> <br\/>    \/\/ Build the output character array<br\/>    for (i = 0; arr[i]; ++i)<br\/>    {<br\/>        output[count[arr[i]]-1] = arr[i];<br\/>        --count[arr[i]];<br\/>    }<br\/> <br\/>    \/\/ Copy the output array to arr, so that arr now<br\/>    \/\/ contains sorted characters<br\/>    for (i = 0; arr[i]; ++i)<br\/>        arr[i] = output[i];<br\/>}<br\/> <br\/>\/\/ Driver program to test above function<br\/>int main()<br\/>{<br\/>    char arr[] = &quot;geeksforgeeks&quot;;\/\/&quot;applepp&quot;;<br\/> <br\/>    countSort(arr);<br\/> <br\/>    printf(&quot;Sorted character array is %s\\n&quot;, arr);<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>JAVA<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Java implementation of Counting Sort<br\/>class CountingSort<br\/>{<br\/>    void sort(char arr[])<br\/>    {<br\/>        int n = arr.length;<br\/> <br\/>        \/\/ The output character array that will have sorted arr<br\/>        char output[] = new char[n];<br\/> <br\/>        \/\/ Create a count array to store count of inidividul<br\/>        \/\/ characters and initialize count array as 0<br\/>        int count[] = new int[256];<br\/>        for (int i=0; i&lt;256; ++i)<br\/>            count[i] = 0;<br\/> <br\/>        \/\/ store count of each character<br\/>        for (int i=0; i&lt;n; ++i)<br\/>            ++count[arr[i]];<br\/> <br\/>        \/\/ Change count[i] so that count[i] now contains actual<br\/>        \/\/ position of this character in output array<br\/>        for (int i=1; i&lt;=255; ++i)<br\/>            count[i] += count[i-1];<br\/> <br\/>        \/\/ Build the output character array<br\/>        for (int i = 0; i&lt;n; ++i)<br\/>        {<br\/>            output[count[arr[i]]-1] = arr[i];<br\/>            --count[arr[i]];<br\/>        }<br\/> <br\/>        \/\/ Copy the output array to arr, so that arr now<br\/>        \/\/ contains sorted characters<br\/>        for (int i = 0; i&lt;n; ++i)<br\/>            arr[i] = output[i];<br\/>    }<br\/> <br\/>    \/\/ Driver method<br\/>    public static void main(String args[])<br\/>    {<br\/>        CountingSort ob = new CountingSort();<br\/>        char arr[] = {&#039;g&#039;, &#039;e&#039;, &#039;e&#039;, &#039;k&#039;, &#039;s&#039;, &#039;f&#039;, &#039;o&#039;,<br\/>                      &#039;r&#039;, &#039;g&#039;, &#039;e&#039;, &#039;e&#039;, &#039;k&#039;, &#039;s&#039;<br\/>                     };<br\/> <br\/>        ob.sort(arr);<br\/> <br\/>        System.out.print(&quot;Sorted character array is &quot;);<br\/>        for (int i=0; i&lt;arr.length; ++i)<br\/>            System.out.print(arr[i]);<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p><strong>PYTHON<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">python<\/span> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Python program for counting sort<br\/> <br\/># The main function that sort the given string arr[] in <br\/># alphabetical order<br\/>def countSort(arr):<br\/> <br\/>    # The output character array that will have sorted arr<br\/>    output = [0 for i in range(256)]<br\/> <br\/>    # Create a count array to store count of inidividul<br\/>    # characters and initialize count array as 0<br\/>    count = [0 for i in range(256)]<br\/> <br\/>    # For storing the resulting answer since the <br\/>    # string is immutable<br\/>    ans = [&quot;&quot; for _ in arr]<br\/> <br\/>    # Store count of each character<br\/>    for i in arr:<br\/>        count[ord(i)] += 1<br\/> <br\/>    # Change count[i] so that count[i] now contains actual<br\/>    # position of this character in output array<br\/>    for i in range(256):<br\/>        count[i] += count[i-1]<br\/> <br\/>    # Build the output character array<br\/>    for i in range(len(arr)):<br\/>        output[count[ord(arr[i])]-1] = arr[i]<br\/>        count[ord(arr[i])] -= 1<br\/> <br\/>    # Copy the output array to arr, so that arr now<br\/>    # contains sorted characters<br\/>    for i in range(len(arr)):<br\/>        ans[i] = output[i]<br\/>    return ans <br\/> <br\/># Driver program to test above function<br\/>arr = &quot;geeksforgeeks&quot;<br\/>ans = countSort(arr)<br\/>print &quot;Sorted character array is %s&quot;  %(&quot;&quot;.join(ans))<br\/> <\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Sorted character array is eeeefggkkorss<\/pre>\n<p><strong>Time Complexity:<\/strong> O(n+k) where n is the number of elements in input array and k is the range of input.<br \/>\n<strong>Auxiliary Space:<\/strong> O(n+k)<\/p>\n<p><strong>Points to be noted:<\/strong><br \/>\n<strong>1.<\/strong> Counting sort is efficient if the range of input data is not significantly greater than the number of objects to be sorted. Consider the situation where the input sequence is between range 1 to 10K and the data is 10, 5, 10K, 5K.<br \/>\n<strong>2.<\/strong> It is not a comparison based sorting. It running time complexity is O(n) with space proportional to the range of data.<br \/>\n<strong>3.<\/strong> It is often used as a sub-routine to another sorting algorithm like radix sort.<br \/>\n<strong>4.<\/strong> Counting sort uses a partial hashing to count the occurrence of the data object in O(1).<br \/>\n<strong>5.<\/strong> Counting sort can be extended to work for negative inputs also.<\/p>\n<p><strong>Exercise:<\/strong><br \/>\n<strong>1.<\/strong> Modify above code to sort the input data in the range from M to N.<br \/>\n<strong>2.<\/strong> Modify above code to sort negative input data.<br \/>\n<strong>3.<\/strong> Is counting sort stable and online?<br \/>\n<strong>4. <\/strong>Thoughts on parallelizing the counting sort algorithm.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Counting sort &#8211; Searching and Sorting &#8211; Counting Sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing).<\/p>\n","protected":false},"author":1,"featured_media":25191,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,71670],"tags":[71894,71852,71847,71840,71893,70263,70268,70461,71121,71879,71122,71884,71874,71877,70780,71833,71869,71891,70497,71868,71885,71875,70271,70928,70017,71225,71881,70262,71262,71872,71889,71289,71892,71886,71878,71267,70046,71145,70977,71266,71870,71844,71857,71858,71846,71843,71880,71120,70016,71883,71697,71873,71890,71674,71308,71125,71695,71871,70020,71882,70652,70019,71887,71876,71888],"class_list":["post-25188","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-algorithm","category-searching-and-sorting","tag-71894","tag-algorithm-for-radix-sort","tag-algorithm-for-radix-sort-in-data-structure","tag-algorithm-of-radix-sort","tag-algorithm-sort","tag-binary-search-tree","tag-binary-tree","tag-bubble-sort","tag-bubble-sort-algorithm","tag-bubble-sort-concept","tag-bubble-sort-java","tag-bubble-sort-online","tag-bubble-sort-technique","tag-bubble-sort-theory","tag-bubblesort","tag-comb-sort","tag-count-python","tag-counting-algorithm","tag-counting-sort","tag-counting-sort-algorithm","tag-decision-tree-sorting","tag-example-of-counting-sort","tag-heap-sort","tag-heap-sort-algorithm","tag-insertion-sort-algorithm","tag-insertion-sort-program","tag-math-sort","tag-merge-sort","tag-merge-sort-algorithm","tag-merge-sort-algorithm-c-code","tag-merge-sort-algorithm-explanation","tag-merge-sort-algorithm-in-c","tag-merge-sort-algorithm-java","tag-pseudocode-for-sorting-algorithms","tag-python-sorting-algorithms","tag-quick-sort-algorithm","tag-quicksort","tag-quicksort-c","tag-quicksort-java","tag-radix-sort-algorithm","tag-radix-sort-algorithm-in-data-structure","tag-radix-sort-algorithm-in-java","tag-radix-sort-algorithm-pseudocode","tag-radix-sort-analysis","tag-radix-sort-applications","tag-radix-sort-code-java","tag-radix-sort-in-c","tag-selection-sort","tag-selection-sort-algorithm","tag-selection-sort-simulation","tag-shell-sort","tag-short-bubble-sort","tag-simple-merge-sort-algorithm","tag-sort","tag-sort-array","tag-sort-code","tag-sorted","tag-sorted-python","tag-sorting-algorithms","tag-sorting-algorithms-explained-with-examples","tag-sorting-algorithms-in-c","tag-sorting-algorithms-in-java","tag-sorting-by-counting","tag-sorting-code-in-c","tag-what-is-merge-sort-algorithm"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25188","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=25188"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25188\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/25191"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25188"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25188"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25188"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}