{"id":6178,"date":"2025-05-29T19:13:38","date_gmt":"2025-05-29T13:43:38","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=6178"},"modified":"2025-06-07T18:34:11","modified_gmt":"2025-06-07T13:04:11","slug":"bubble-sort","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/bubble-sort\/","title":{"rendered":"Bubble Sort"},"content":{"rendered":"\n<!-- Prism.js CSS and JS -->\n<link href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.css\" rel=\"stylesheet\" \/>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.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_code-tabs-container {\n    font-family: \"Segoe UI\", sans-serif !important;\n    max-width: 900px !important;\n    margin: 2rem auto !important;\n    border: 1px solid #ddd !important;\n    border-radius: 8px !important;\n    overflow: hidden !important;\n    background-color: white !important;\n}\n\n.wp_blog_code-tabs-header {\n    background: #f7f7f7 !important;\n    display: flex !important;\n    border-bottom: 1px solid #ddd !important;\n}\n\n.wp_blog_code-tab-button {\n    flex: 1 !important;\n    padding: 10px 15px !important;\n    border: none !important;\n    background: transparent !important;\n    cursor: pointer !important;\n    font-weight: bold !important;\n    transition: background 0.2s !important;\n    color: #242B33 !important;\n}\n\n.wp_blog_code-tab-button.active {\n    background: white !important;\n    border-bottom: 3px solid #0073aa !important;\n}\n\n.wp_blog_code-tab-content {\n    display: none !important;\n    padding: 20px !important;\n    background: #242B33 !important;\n}\n\n.wp_blog_code-tab-content > pre {\n    background: #242B33 !important;\n}\n\n.wp_blog_code-tab-content.active {\n    display: block !important;\n}\n\n.wp_blog_code-tab-content pre {\n    margin: 0 !important;\n    overflow-x: auto !important;\n}\n\n.wp_blog_explanation {\n    max-width: 900px !important;\n    margin: 2rem auto !important;\n    font-family: \"Segoe UI\", sans-serif !important;\n    line-height: 1.6 !important;\n    background: white !important;\n    color: black !important;\n    padding: 1rem !important;\n    border-radius: 8px !important;\n}\n\n.wp_blog_explanation h2 {\n    color: #0073aa !important;\n    font-size: 1.5rem !important;\n    margin-bottom: 0.5rem !important;\n}\n\n.wp_blog_explanation code {\n    background: #f1f1f1 !important;\n    padding: 2px 6px !important;\n    border-radius: 4px !important;\n    font-family: monospace !important;\n}\n\n.wp_blog_explanation h1,\n.wp_blog_explanation h2,\n.wp_blog_explanation h3,\n.wp_blog_explanation h4,\n.wp_blog_explanation h5,\n.wp_blog_explanation h6,\n.wp_blog_explanation p {\n    margin-top: 10px !important;\n    margin-bottom: 10px !important;\n}\n<\/style>\n\n<!-- \u2705 START: Blog Explanation -->\n\n\n  <div  class=\"wp_blog_explanation\">\n\n   \n    <p>\n      Bubble Sort is a simple sorting algorithm that repeatedly steps through the list,\n      compares adjacent elements, and swaps them if they are in the wrong order. This\n      process is repeated until the array is sorted. After each pass, the largest unsorted\n      element &#8220;bubbles up&#8221; to its correct position at the end of the array. It&#8217;s called\n      &#8220;Bubble Sort&#8221; because smaller elements slowly &#8220;bubble&#8221; to the top of the list.\n    <\/p>\n  \n    <h2>Approach:<\/h2>\n    <ul>\n      <li>Iterate through the array multiple times.<\/li>\n      <li>In each pass, compare adjacent elements:\n        <ul>\n          <li>If the current element is greater than the next one, swap them.<\/li>\n          <li>After each pass, the largest unsorted element bubbles up to its correct position at the end.<\/li>\n        <\/ul>\n      <\/li>\n      <li>Use a boolean flag (<code>isSwapped<\/code>) to track whether any swapping happened:\n        <ul>\n          <li>If no swaps occurred in a full pass, the array is already sorted \u2192 early exit (optimization).<\/li>\n        <\/ul>\n      <\/li>\n      <li>Repeat this process for <code>n - 1<\/code> passes (where <code>n<\/code> is the array length), or until no swaps are needed.<\/li>\n    <\/ul>\n  \n    <h2>Dry Run (arr = [3, 1, 4]):<\/h2>\n    <pre>\n  Initial State: [3, 1, 4]\n  \n  Pass 1 (i = 0):\n  j = 0: Compare arr[0] = 3 and arr[1] = 1\n   \u2192 3 > 1 \u2192 swap\n   \u2192 arr = [1, 3, 4]\n  \n  j = 1: Compare arr[1] = 3 and arr[2] = 4\n   \u2192 3 < 4 \u2192 no swap\n  \n  \u2192 At least one swap was made, so continue.\n  \n  Pass 2 (i = 1):\n  j = 0: Compare arr[0] = 1 and arr[1] = 3\n   \u2192 1 < 3 \u2192 no swap\n  \n  \u2192 No swaps made \u2192 array is sorted \u2192 exit early\n    <\/pre>\n  \n    <h2>Time Complexity:<\/h2>\n    <ul>\n      <li><strong>Best Case:<\/strong> O(n) \u2192 when array is already sorted (optimized with <code>isSwapped<\/code>)<\/li>\n      <li><strong>Worst Case:<\/strong> O(n\u00b2) \u2192 when array is in reverse order<\/li>\n    <\/ul>\n  \n    <h2>Space Complexity:<\/h2>\n    <ul>\n      <li>O(1) \u2192 In-place sorting, no extra space used<\/li>\n    <\/ul>\n  \n  <\/div>\n  \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\">JavaScript<\/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=\"java\">Java<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n      <pre><code class=\"language-javascript\">\n  let arr = [4,5,1,3,9]\n  \n  function bubbleSort(arr){\n    let n = arr.length;\n    for(let i=0; i&lt;n-1; i++) {\n      let isSwapped = false;\n      for(let j=0; j&lt;n-1-i; j++) {\n        if(arr[j]&gt;arr[j+1]) {\n          let temp=arr[j]\n          arr[j]=arr[j+1];\n          arr[j+1]=temp;\n          isSwapped=true;\n        }\n      }\n      if(!isSwapped)\n        break;\n    }\n    return arr;\n  }\n  let result = bubbleSort(arr)\n  console.log(\"Sorted array\",result)\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n      <pre><code class=\"language-cpp\">\n  #include &lt;iostream&gt;\n  using namespace std;\n  \n  void bubbleSort(int arr[], int n) {\n    for (int i = 0; i &lt; n - 1; i++) {\n      bool isSwapped = false;\n      for (int j = 0; j &lt; n - 1 - i; j++) {\n        if (arr[j] &gt; arr[j + 1]) {\n          swap(arr[j], arr[j + 1]);\n          isSwapped = true;\n        }\n      }\n      if (!isSwapped) break;\n    }\n  }\n  \n  int main() {\n    int arr[] = {4, 5, 1, 3, 9};\n    int n = sizeof(arr) \/ sizeof(arr[0]);\n    bubbleSort(arr, n);\n    cout &lt;&lt; \"Sorted array: \";\n    for (int i = 0; i &lt; n; i++) cout &lt;&lt; arr[i] &lt;&lt; \" \";\n    return 0;\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  #include &lt;stdbool.h&gt;\n  \n  void bubbleSort(int arr[], int n) {\n    for (int i = 0; i &lt; n - 1; i++) {\n      bool isSwapped = false;\n      for (int j = 0; j &lt; n - 1 - i; j++) {\n        if (arr[j] &gt; arr[j + 1]) {\n          int temp = arr[j];\n          arr[j] = arr[j + 1];\n          arr[j + 1] = temp;\n          isSwapped = true;\n        }\n      }\n      if (!isSwapped) break;\n    }\n  }\n  \n  int main() {\n    int arr[] = {4, 5, 1, 3, 9};\n    int n = sizeof(arr) \/ sizeof(arr[0]);\n    bubbleSort(arr, n);\n    printf(\"Sorted array: \");\n    for (int i = 0; i &lt; n; i++) printf(\"%d \", arr[i]);\n    return 0;\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n      <pre><code class=\"language-java\">\n  public class Solution {\n    public static void bubbleSort(int[] arr) {\n      int n = arr.length;\n      for (int i = 0; i &lt; n - 1; i++) {\n        boolean isSwapped = false;\n        for (int j = 0; j &lt; n - 1 - i; j++) {\n          if (arr[j] &gt; arr[j + 1]) {\n            int temp = arr[j];\n            arr[j] = arr[j + 1];\n            arr[j + 1] = temp;\n            isSwapped = true;\n          }\n        }\n        if (!isSwapped) break;\n      }\n    }\n  \n    public static void main(String[] args) {\n      int[] arr = {4, 5, 1, 3, 9};\n      bubbleSort(arr);\n      System.out.print(\"Sorted array: \");\n      for (int num : arr) System.out.print(num + \" \");\n    }\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n      <pre><code class=\"language-python\">\n  def bubbleSort(arr):\n    n = len(arr)\n    for i in range(n - 1):\n      is_swapped = False\n      for j in range(n - 1 - i):\n        if arr[j] &gt; arr[j + 1]:\n          arr[j], arr[j + 1] = arr[j + 1], arr[j]\n          is_swapped = True\n      if not is_swapped:\n        break\n    return arr\n  \n  arr = [4, 5, 1, 3, 9]\n  print(\"Sorted array:\", bubbleSort(arr))\n      <\/code><\/pre>\n    <\/div>\n  <\/div>\n  \n  \n  \n  \n  \n<!-- \u2705 JS Tab Switch Logic -->\n<script>\ndocument.addEventListener('DOMContentLoaded', function () {\n    const buttons = document.querySelectorAll('.wp_blog_code-tab-button');\n    const contents = document.querySelectorAll('.wp_blog_code-tab-content');\n    buttons.forEach(button => {\n        button.addEventListener('click', () => {\n            const lang = button.getAttribute('data-lang');\n            buttons.forEach(btn => btn.classList.remove('active'));\n            button.classList.add('active');\n            contents.forEach(content => {\n                content.classList.toggle('active', content.getAttribute('data-lang') === lang);\n            });\n        });\n    });\n});\n<\/script>\n","protected":false},"excerpt":{"rendered":"<p>Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the array is sorted. After each pass, the largest unsorted element &#8220;bubbles up&#8221; to its correct position at the end of the array. It&#8217;s<\/p>\n","protected":false},"author":1,"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":[811,810],"tags":[],"class_list":{"0":"post-6178","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-data-structures-and-algorithms","7":"category-dsa"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6178","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\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=6178"}],"version-history":[{"count":2,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6178\/revisions"}],"predecessor-version":[{"id":6496,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6178\/revisions\/6496"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=6178"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=6178"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=6178"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}