{"id":11473,"date":"2026-02-04T23:04:15","date_gmt":"2026-02-04T17:34:15","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=11473"},"modified":"2026-02-06T22:27:00","modified_gmt":"2026-02-06T16:57:00","slug":"counting-sort","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/counting-sort\/","title":{"rendered":"Counting Sort"},"content":{"rendered":"\n<!-- PrismJS for Syntax Highlighting -->\n<link\n    href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.min.css\"\n    rel=\"stylesheet\"\n\/>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.min.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n.wp_blog_theme {\n  --primary: #E58C32;\n  --secondary: #030302;\n  --light-bg: #fef9f4;\n  --text-dark: #2d2d2d;\n  --tab-radius: 12px;\n  --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n  --code-bg: #001f3f;\n  --code-text: #d4f1ff;\n}\n\n.wp_blog_container {\n  font-family: 'Segoe UI', sans-serif;\n  background: var(--light-bg);\n  margin: 0;\n  padding: 0;\n  color: var(--text-dark);\n}\n\n\/* Heading *\/\n.wp_blog_main-heading {\n  text-align: center;\n  font-size: 2.4rem;\n  color: var(--primary);\n  margin-top: 2.5rem;\n  font-weight: bold;\n}\n\n\/* Explanation Card *\/\n.wp_blog_explanation,\n.wp_blog_code-tabs-container {\n  max-width: 940px;\n  margin: 2rem auto;\n  padding: 2rem;\n  background: white;\n  border-radius: var(--tab-radius);\n  box-shadow: var(--shadow);\n}\n\n\/* Text and Visuals *\/\n.wp_blog_explanation h2 {\n  font-size: 1.4rem;\n  color: var(--primary);\n  margin-bottom: 0.5rem;\n}\n\n.wp_blog_explanation p,\n.wp_blog_explanation li {\n  font-size: 1.05rem;\n  line-height: 1.7;\n  margin: 0.5rem 0;\n}\n\n.wp_blog_explanation code {\n  background: #fef9f4;   \/* light bg instead of dark blue *\/\n  color: #E58C32;        \/* brand orange *\/\n  padding: 3px 6px;\n  border-radius: 4px;\n  font-family: 'Courier New', monospace;\n  font-weight: 600;      \/* optional, makes it pop *\/\n}\n\n.wp_blog_explanation img {\n  max-width: 100%;\n  border-radius: var(--tab-radius);\n  margin-top: 1rem;\n  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);\n}\n\n\/* Tab Buttons *\/\n.wp_blog_code-tabs-header {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 0.5rem;\n  margin-bottom: 1rem;\n}\n\n.wp_blog_code-tab-button {\n  padding: 0.6rem 1.2rem;\n  border: 1px solid var(--primary);\n  background: white;\n  color: var(--primary);\n  border-radius: 50px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: all 0.3s ease;\n}\n\n.wp_blog_code-tab-button:hover {\n  background: var(--secondary);\n}\n\n.wp_blog_code-tab-button.active {\n  background: var(--primary);\n  color: white;\n}\n\n\/* Code Content *\/\n.wp_blog_code-tab-content {\n  display: none;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n}\n\n.wp_blog_code-tab-content.active {\n  display: block;\n}\n\n.wp_blog_code-tab-content pre {\n  margin: 0;\n  padding: 1.5rem;\n  font-size: 1rem;\n  overflow-x: auto;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n  color: var(--code-text);\n}\n\n\/* Dark mode variables *\/\n.wp_blog_theme.dark-mode {\n  --light-bg: #121212;\n  --text-dark: #f5f5f5;\n  --shadow: 0 4px 12px rgba(255, 255, 255, 0.08);\n  --code-bg: #1e1e1e;\n  --code-text: #c5f0ff;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_explanation {\n  background: #1e1e1e;\n}\n\n\/* Dark mode code highlight *\/\n.wp_blog_theme.dark-mode .wp_blog_explanation code {\n  background: #333;\n  color: #ffd27f;\n}\n\n.wp_blog_theme {\n  position: relative; \/* makes it the reference for absolute children *\/\n}\n\n.wp_blog_toggle-btn {\n  position: absolute;\n  top: 1rem;\n  right: 1rem;\n  z-index: 9999;\n  padding: 0.5rem 0.8rem;\n  border-radius: 10%;\n  background: var(--primary);\n  color: white;\n  font-weight: bold;\n  cursor: pointer;\n  border: none;\n  box-shadow: var(--shadow);\n  transition: background 0.3s, transform 0.2s;\n}\n\n.wp_blog_toggle-btn:hover {\n  background: #cc772e;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_code-tabs-container {\n  background: #1e1e1e;\n}\n<\/style>\n\n<div class=\"wp_blog_container wp_blog_theme\">\n            <button id=\"blogNotesThemeToggle\" class=\"wp_blog_toggle-btn\">\ud83c\udf19<\/button>\n\n<h1 class=\"wp_blog_main-heading\"><\/h1>\n\n<div class=\"wp_blog_explanation\">\n    <h2>Counting Sort<\/h2>\n    <p> Counting Sort is a <strong>non-comparison based sorting algorithm<\/strong>.\n    It works by counting how many times each element appears, then reconstructing the sorted array using those counts.\n    <\/p>\n    <p><strong>Best when: <\/strong>\n    <p>Numbers are non-negative integers.<\/p>\n    <p>Range (max &#8211; min) is small.<\/p>\n    <\/p>\n\n    <img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2026\/02\/Screenshot-2026-02-04-at-10.47.18-PM.png\" alt=\"\">\n\n    <h2>Time Complexity<\/h2>\n    <p><strong>O(n + k)<\/strong><\/p>\n    <p>where k: range.<\/p>\n    <p><i>If &#8216;k&#8217; (range) is small, then this algorithm is efficient.<\/i><\/p>\n\n    <h2>Space Complexity<\/h2>\n    <p><strong>O(K)<\/strong><\/p>\n\n    <h2>Points to remember while using this algorithm<\/h2>\n    <p><strong><code>Elements are integers.<\/code><\/strong><\/p>\n    <p><strong><code>Values are small in range.<\/code><\/strong><\/p>\n\n    <h2>Examples<\/h2>\n    <ul>\n        <li>Marks of students (0 to 100) (range)<\/li>\n        <li>Percentages<\/li>\n        <li>Sort based on Ages (0-120)<\/li>\n        <li>Digits(0 &#8211; 9)<\/li>\n    <\/ul>\n    <h2>Disadvantage<\/h2>\n    <p><strong>Not Stable algorithm<\/strong><\/p>\n    <h2>Reasons:<\/h2>\n    <ul>\n        <li>We only count frequencies.<\/li>\n        <li>Then we overwrite the original array.<\/li>\n        <li>We don\u2019t remember the original order of equal elements.<\/li>\n        <li>So if two elements have the same value, their relative order may change.<\/li>\n    <\/ul>\n<\/div>\n\n<div class=\"wp_blog_code-tabs-container\">\n    <div class=\"wp_blog_code-tabs-header\">\n        <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">\n            JavaScript\n        <\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"cs\">C#<\/button>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n       \n<pre><code class=\"language-javascript\">\nfunction countingSort(arr) {\n    let max = Math.max(...arr);\n\n    let count = new Array(max + 1).fill(0);\n\n    for (let x of arr) {\n        count[x]++;\n    }\n\n    let index = 0;\n    for (let i = 0; i < count.length; i++) {\n        while (count[i] > 0) {\n            arr[index] = i;\n            index++;\n            count[i]--;\n        }\n    }\n\n    return arr;\n}\n\nlet nums = [4, 2, 5, 3, 3, 2, 1, 4];\nconsole.log(countingSort(nums));\n\n<\/code><\/pre>\n\n<\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n        <pre><code class=\"language-python\">\ndef counting_sort(arr):\n    max_val = max(arr)\n    count = [0] * (max_val + 1)\n\n    for x in arr:\n        count[x] += 1\n\n    index = 0\n    for i in range(len(count)):\n        while count[i] > 0:\n            arr[index] = i\n            index += 1\n            count[i] -= 1\n\n    return arr\n\n\nnums = [4, 2, 5, 3, 3, 2, 1, 4]\nprint(counting_sort(nums))\n    <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n        <pre><code class=\"language-java\">\nimport java.util.*;\n\npublic class CountingSort {\n    public static int[] countingSort(int[] arr) {\n        int max = Arrays.stream(arr).max().getAsInt();\n\n        int[] count = new int[max + 1];\n\n        for (int x : arr) {\n            count[x]++;\n        }\n\n        int index = 0;\n        for (int i = 0; i < count.length; i++) {\n            while (count[i] > 0) {\n                arr[index++] = i;\n                count[i]--;\n            }\n        }\n        return arr;\n    }\n\n    public static void main(String[] args) {\n        int[] nums = {4, 2, 5, 3, 3, 2, 1, 4};\n        System.out.println(Arrays.toString(countingSort(nums)));\n    }\n}\n\n<\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n        <pre><code class=\"language-cpp\">\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n\nusing namespace std;\n\nvector<int> countingSort(vector<int>& arr) {\n    int maxVal = *max_element(arr.begin(), arr.end());\n\n    vector<int> count(maxVal + 1, 0);\n\n    for (int x : arr) {\n        count[x]++;\n    }\n\n    int index = 0;\n    for (int i = 0; i < count.size(); i++) {\n        while (count[i] > 0) {\n            arr[index++] = i;\n            count[i]--;\n        }\n    }\n    return arr;\n}\n\nint main() {\n    vector<int> nums = {4, 2, 5, 3, 3, 2, 1, 4};\n    nums = countingSort(nums);\n\n    for (int x : nums)\n        cout << x << \" \";\n}\n    <\/code><\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n        <pre><code class=\"language-c\">\n#include &lt;stdio.h&gt;\n\nvoid countingSort(int arr[], int n) {\n    int max = arr[0];\n    for (int i = 1; i < n; i++)\n        if (arr[i] > max)\n            max = arr[i];\n\n    int count[max + 1];\n    for (int i = 0; i <= max; i++)\n        count[i] = 0;\n\n    for (int i = 0; i < n; i++)\n        count[arr[i]]++;\n\n    int index = 0;\n    for (int i = 0; i <= max; i++) {\n        while (count[i] > 0) {\n            arr[index++] = i;\n            count[i]--;\n        }\n    }\n}\n\nint main() {\n    int nums[] = {4, 2, 5, 3, 3, 2, 1, 4};\n    int n = sizeof(nums) \/ sizeof(nums[0]);\n\n    countingSort(nums, n);\n\n    for (int i = 0; i < n; i++)\n        printf(\"%d \", nums[i]);\n\n    return 0;\n}\n    <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n        <pre><code class=\"language-csharp\">\nusing System;\nusing System.Linq;\n\nclass CountingSortExample {\n    static int[] CountingSort(int[] arr) {\n        int max = arr.Max();\n        int[] count = new int[max + 1];\n\n        foreach (int x in arr)\n            count[x]++;\n\n        int index = 0;\n        for (int i = 0; i < count.Length; i++) {\n            while (count[i] > 0) {\n                arr[index++] = i;\n                count[i]--;\n            }\n        }\n        return arr;\n    }\n\n    static void Main() {\n        int[] nums = {4, 2, 5, 3, 3, 2, 1, 4};\n        nums = CountingSort(nums);\n        Console.WriteLine(string.Join(\" \", nums));\n    }\n}\n  <\/code><\/pre>\n    <\/div>\n<\/div>\n<\/div>\n<script>\ndocument.addEventListener(\"DOMContentLoaded\", () => {\n  const buttons = document.querySelectorAll(\".wp_blog_code-tab-button\");\n  const contents = document.querySelectorAll(\".wp_blog_code-tab-content\");\n\n  buttons.forEach((button) => {\n    button.addEventListener(\"click\", () => {\n      const lang = button.getAttribute(\"data-lang\");\n\n      buttons.forEach((btn) => btn.classList.remove(\"active\"));\n      contents.forEach((content) => content.classList.remove(\"active\"));\n\n      button.classList.add(\"active\");\n      document\n        .querySelector(`.wp_blog_code-tab-content[data-lang=\"${lang}\"]`)\n        .classList.add(\"active\");\n    });\n  });\n\n  const themeToggle = document.getElementById(\"blogNotesThemeToggle\");\n  const themeContainer = document.querySelector(\".wp_blog_theme\");\n\n  themeToggle.addEventListener(\"click\", () => {\n    themeContainer.classList.toggle(\"dark-mode\");\n    themeToggle.textContent =\n      themeContainer.classList.contains(\"dark-mode\") ? \"\u2600\ufe0f\" : \"\ud83c\udf19\";\n  });\n});\n<\/script>\n","protected":false},"excerpt":{"rendered":"<p>\ud83c\udf19 Counting Sort Counting Sort is a non-comparison based sorting algorithm. It works by counting how many times each element appears, then reconstructing the sorted array using those counts. Best when: Numbers are non-negative integers. Range (max &#8211; min) is small. Time Complexity O(n + k) where k: range. If &#8216;k&#8217; (range) is small, then<\/p>\n","protected":false},"author":108,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[210,322,260,176,175,211,811,810,174,172],"tags":[],"class_list":{"0":"post-11473","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-algorithms","7":"category-algorithms-and-data-structures","8":"category-c-c-plus-plus","9":"category-csharp","10":"category-cplusplus","11":"category-data-structures","12":"category-data-structures-and-algorithms","13":"category-dsa","14":"category-java","15":"category-javascript"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/11473","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/108"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=11473"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/11473\/revisions"}],"predecessor-version":[{"id":11474,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/11473\/revisions\/11474"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=11473"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=11473"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=11473"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}