{"id":132,"date":"2026-07-14T08:19:32","date_gmt":"2026-07-14T08:19:32","guid":{"rendered":"https:\/\/blog.csfree.org\/?p=132"},"modified":"2026-07-14T08:27:41","modified_gmt":"2026-07-14T08:27:41","slug":"bubble-sort","status":"publish","type":"post","link":"https:\/\/blog.csfree.org\/index.php\/2026\/07\/14\/bubble-sort\/","title":{"rendered":"How Bubble Sort Works (And Why It Takes Its Time)"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">How Bubble Sort Works (And Why It Takes Its Time)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is Sorting?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">At its core, <strong>sorting<\/strong> is just the process of <strong>arranging <\/strong>a messy collection of items into a specific, meaningful order.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here are two examples of sorting, we go through every day life:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Numerical Order:<\/strong> Arranging numbers from smallest to largest (1, 2, 3&#8230;) or largest to smallest (99, 98, 97&#8230;).<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Alphabetical Order:<\/strong> Arranging words or strings from A to Z (like a phonebook contact list) or Z to A.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Why do we code to Sort through?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Computers don&#8217;t sort data just to make it look neat. They do it because <strong>sorted data is incredibly fast to work with<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Think about trying to find a specific word in a massive dictionary. If the dictionary were printed in a completely random order, you would have to read every single page from start to finish just to find one definition. Because it is strictly sorted from A to Z, your brain instantly knows how to skip straight to the section you need.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the exact same way, sorting turns a chaotic mess of data into an organized system that algorithms can search through, analyze, and process in milliseconds. Bubble Sort is just one of many different strategies, or <strong>algorithms<\/strong>, we use to get that data in order.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is this <strong>Bubble <\/strong>Sort?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Imagine you have a playlist of songs, and you want to order them from your absolute least favorite to your ultimate favorite. <strong>Bubble Sort <\/strong>works like a lazy listener. It compares just the first two tracks. If track two is better, they swap places. Then it compares track two and three, swapping again if needed. By the time you listen all the way to the end of the playlist, your #1 favorite song has naturally drifted, or <em><strong>bubbled<\/strong><\/em> all the way to the very top.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In computer science, <strong>Bubble Sort<\/strong> (sometimes referred to as <strong>sinking sort<\/strong>) is a fundamental, comparison-based sorting algorithm. It operates on a simple iterative principle: it repeatedly steps through a data structure, compares adjacent elements, and swaps them if they are in the wrong order.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">While we speak about Bubble Sort, we have to keep three point in mind!<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>The Mechanics of the Passes<\/strong>:<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The algorithm gets its name because smaller or larger elements &#8220;bubble&#8221; to the top of the data structure after each iteration (or &#8220;pass&#8221;). During a single pass, the algorithm runs a loop from index 0 to (n-1). With each comparison, the larger value is pushed forward. Consequently, <strong>each full pass guarantees that the next highest unsorted value settles into its final, permanently correct position at the end of the array<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong> Time Complexity: The Cost of Nested Loops<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Bubble Sort <\/strong>relies on two nested loops: an outer loop to track the number of passes, and an inner loop to compare adjacent items.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Worst-Case Complexity (O(<math data-latex=\"n^2\"><semantics><msup><mi>n<\/mi><mn>2<\/mn><\/msup><annotation encoding=\"application\/x-tex\">n^2<\/annotation><\/semantics><\/math>)):<\/strong> Occurs when the input array is sorted in completely reverse order. The algorithm must perform the maximum number of comparisons and swaps, resulting in a quadratic time scale (<math data-latex=\"\\frac{n(n-1)}{2}\"><semantics><mfrac><mrow><mi>n<\/mi><mo form=\"prefix\" stretchy=\"false\">(<\/mo><mi>n<\/mi><mo>\u2212<\/mo><mn>1<\/mn><mo form=\"postfix\" stretchy=\"false\" lspace=\"0em\" rspace=\"0em\">)<\/mo><\/mrow><mn>2<\/mn><\/mfrac><annotation encoding=\"application\/x-tex\">\\frac{n(n-1)}{2}<\/annotation><\/semantics><\/math> total comparisons).<\/li>\n\n\n\n<li><strong>Average-Case Complexity (O(<\/strong><math data-latex=\"n^2\"><semantics><msup><mi>n<\/mi><mn>2<\/mn><\/msup><annotation encoding=\"application\/x-tex\">n^2<\/annotation><\/semantics><\/math><strong>)):<\/strong> Occurs when the data is randomly distributed.<\/li>\n\n\n\n<li><strong>Best-Case Complexity (O(n)):<\/strong> Occurs when the array is <em>already<\/em> fully sorted. If optimized with a boolean flag that tracks whether a swap happened during a pass, the algorithm can realize the array is sorted and terminate early after just one single pass of (n-1) comparisons.<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Space Complexity and Memory Efficiency<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Bubble Sort is classified as an <strong>in-place algorithm<\/strong>. It manipulates the data directly inside the original array pointer without allocating auxiliary memory that scales with the input size. Because it only requires a single temporary variable to handle the swapping mechanism, its space complexity is a highly efficient <strong>O(1) (constant space)<\/strong>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step-by-Step Example<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s sort a small, unsorted array of numbers in ascending order: <code>[5, 1, 4, 2, 8, 0]<\/code><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 1: The First Big Walkthrough<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Starting array <em>:<\/em> <code>[5, 1, 4, 2, 8, 0]<\/code><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Compare 5 and 1<\/strong> : Is 5 &gt; 1? Yes -&gt; Swap -&gt; <code>[1, 5, 4, 2, 8, 0]<\/code><\/li>\n\n\n\n<li><strong>Compare 5 and 4<\/strong> : Is 5 &gt; 4? Yes -&gt; Swap -&gt; <code>[1, 4, 5, 2, 8, 0]<\/code><\/li>\n\n\n\n<li><strong>Compare 5 and 2<\/strong> : Is 5 &gt; 2? Yes -&gt; Swap -&gt; <code>[1, 4, 2, 5, 8, 0]<\/code><\/li>\n\n\n\n<li><strong>Compare 5 and 8<\/strong> : Is 5 &gt; 8? No -&gt; Keep -&gt; <code>[1, 4, 2, 5, 8, 0]<\/code><\/li>\n\n\n\n<li><strong>Compare 8 and 0<\/strong> : Is 8 &gt; 0? Yes -&gt; Swap -&gt; <code>[1, 4, 2, 5, 0, 8]<\/code><\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>End of Pass 1:<\/strong> The largest number (<strong>8<\/strong>) has successfully bubbled to the very end. It is now locked into place.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 2: Finding the Next Largest<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Active boundary<em>:<\/em> <code>[1, 4, 2, 5, 0]<\/code> (We ignore index 5 where 8 is)<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Compare 1 and 4:<\/strong> Is 1 &gt; 4? No -&gt; Keep -&gt; (<code>[1, 4, 2, 5, 0, 8]<\/code>)<\/li>\n\n\n\n<li><strong>Compare 4 and 2:<\/strong> Is 4 &gt; 2? Yes -&gt; Swap -&gt; (<code>[1, 2, 4, 5, 0, 8]<\/code>)<\/li>\n\n\n\n<li><strong>Compare 4 and 5:<\/strong> Is 4 &gt; 5? No -&gt; Keep -&gt; (<code>[1, 2, 4, 5, 0, 8]<\/code>)<\/li>\n\n\n\n<li><strong>Compare 5 and 0:<\/strong> Is 5 &gt; 0? Yes -&gt; Swap -&gt; (<code>[1, 2, 4, 0, 5, 8]<\/code>)<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>End of Pass 2:<\/strong> The next largest number (<strong>5<\/strong>) is locked into place.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 3: Shrinking the Window<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Active boundary:<\/em> <code>[1, 2, 4, 0]<\/code> (We now ignore 5 and 8)<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Compare 1 and 2:<\/strong> Is 1 &gt; 2? No -&gt; Keep -&gt; (<code>[1, 2, 4, 0, 5, 8]<\/code>)<\/li>\n\n\n\n<li><strong>Compare 2 and 4:<\/strong> Is -&gt; 2 &gt; 4? No -&gt; Keep -&gt; (<code>[1, 2, 4, 0, 5, 8]<\/code>)<\/li>\n\n\n\n<li><strong>Compare 4 and 0:<\/strong> Is 4 &gt; 0? Yes -&gt; Swap -&gt;(<code>[1, 2, 0, 4, 5, 8]<\/code>)<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>End of Pass 3:<\/strong> The number <strong>4<\/strong> is locked into place.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 4: Getting Closer<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Active boundary:<\/em> <code>[1, 2, 0]<\/code><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Compare 1 and 2:<\/strong> Is 1 &gt; 2? No -&gt; Keep -&gt; (<code>[1, 2, 0, 4, 5, 8]<\/code>)<\/li>\n\n\n\n<li><strong>Compare 2 and 0:<\/strong> Is 2 &gt; 0? Yes -&gt; Swap -&gt; (<code>[1, 0, 2, 4, 5, 8]<\/code>)<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>End of Pass 4:<\/strong> The number <strong>2<\/strong> is locked into place.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Pass 5: The Final Swap<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Active boundary:<\/em> <code>[1, 0]<\/code><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Compare 1 and 0:<\/strong> Is 1 &gt; 0? Yes -&gt; Swap -&gt; (<code>[0, 1, 2, 4, 5, 8]<\/code>)<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>End of Pass 5:<\/strong> The number <strong>1<\/strong> is locked into place.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Pass 6: The Safety Check<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Active boundary:<\/em> <code>[0]<\/code><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The algorithm does one final look at the remaining unsorted element. Since there is only one element left, or because it runs a final check pass and detects <strong>zero swaps<\/strong>, it knows the array is officially completely sorted.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Final Sorted Array:<\/strong> <code>[0, 1, 2, 4, 5, 8]<\/code><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example:<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Following is a program of the general <strong>Bubble Sorting<\/strong>. (in C++)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;utility&gt; \/\/ Required for std::swap\n\nvoid bubbleSort(std::vector&lt;int&gt;&amp; arr) {\n    int n = arr.size();\n    bool swapped;\n    \n    \/\/ Outer loop: controls the number of passes\n    for (int i = 0; i &lt; n - 1; i++) {\n        swapped = false;\n        \n        \/\/ Inner loop: compares adjacent elements\n        \/\/ (n - i - 1) stops us from checking already sorted numbers at the end<\/strong>\n<strong>\n        for (int j = 0; j &lt; n - i - 1; j++) {\n            if (arr&#91;j] &gt; arr&#91;j + 1]) {\n                \/\/ Use standard library swap function\n                std::swap(arr&#91;j], arr&#91;j + 1]);\n                swapped = true; \/\/ Mark that a swap occurred\n            }\n        }\n        \n        \/\/ Optimization: if no elements were swapped, the array is already sorted\n        if (!swapped) {\n            break;\n        }\n    }\n}\n\n\/\/ Helper function to print the vector layout\nvoid printVector(const std::vector&lt;int&gt;&amp; arr) {\n    for (int num : arr) {\n        std::cout &lt;&lt; num &lt;&lt; \" \";\n    }\n    std::cout &lt;&lt; \"\\n\";\n}\n\nint main() {\n    std::vector&lt;int&gt; numbers = {5, 1, 4, 2, 8, 0};\n    \n    std::cout &lt;&lt; \"Original Array: \";\n    printVector(numbers);\n    \n    bubbleSort(numbers);\n    \n    std::cout &lt;&lt; \"Sorted Array:   \";\n    printVector(numbers);\n    \n    return 0;\n}<\/strong><\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Using this piece of code, you will be easily be able to sort through a vast variety of number, in <strong>Ascending Order<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">What do you think, the sorting will look like for the <strong>Descending Order<\/strong>?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The amazing thing is-<br>Almost the whole peice will be very similar to that of the <strong>Ascending Order<\/strong>, except the change is-<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>\/\/ Inner loop: compares adjacent elements\nfor (int j = 0; j &lt; n - i - 1; j++) {\n    \/\/ Flipped to '&lt;' to push smaller elements to the end of the vector\n    if (arr&#91;j] &lt; arr&#91;j + 1]) { \n        std::swap(arr&#91;j], arr&#91;j + 1]);\n        swapped = true; \n    }\n}<\/strong><\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The above peice of code gives the numbers in a <strong>Descending Order<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Although usefull, <strong>Bubble Sort <\/strong>is QUITE <strong>disadvantageous<\/strong>, mainly due to-<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Terrible Time Complexity (O(<\/strong><math data-latex=\"n^2\"><semantics><msup><mi>n<\/mi><mn>2<\/mn><\/msup><annotation encoding=\"application\/x-tex\">n^2<\/annotation><\/semantics><\/math>))<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Because it uses nested loops, the time it takes to sort grows drastically as your dataset gets larger. If you double the size of your array, it takes <strong>four times<\/strong> longer to execute. If you have suppose, <strong>10,000 items<\/strong>, it has to perform up to roughly <strong>100,000,000<\/strong> (one hundred million) comparisons. Other algorithms like <strong>Merge Sort<\/strong> or <strong>Quick Sort<\/strong> handle this in a fraction of a millisecond using <strong>O(n log n)<\/strong> time.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Way Too Many Swaps<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Unlike <strong>Selection Sort <\/strong>(which only swaps elements once per pass), <strong>Bubble Sort<\/strong> swaps elements continuously. Modifying data in memory over and over again consumes CPU cycles, making it incredibly slow and memory-thrashing in practice.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So, in Conclusion, <strong>Bubble Sort<\/strong> is an educational tool, not a practical one. It&#8217;s perfect for training your brain to understand loops and swapping mechanics, but highly inefficient for real-world apps with big data.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Tip<\/strong>: <strong>Bubble Sort<\/strong> is an educational tool, not a practical one. It&#8217;s perfect for training your brain to understand loops and swapping mechanics, but highly inefficient for real-world apps with big data.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>How Bubble Sort Works (And Why It Takes Its Time) What is Sorting? At its core, sorting is just the [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"disabled","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[66,49,50],"tags":[57,59,55,65,61,60,52,53,54,56,58],"class_list":["post-132","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-data-structures","category-sorting","tag-algorithms","tag-big-o-notation","tag-bubble-sort","tag-c","tag-computer-science","tag-data-structures","tag-datastructures","tag-dsa","tag-sorting","tag-sorting-algorithms","tag-time-complexity"],"_links":{"self":[{"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/posts\/132","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/comments?post=132"}],"version-history":[{"count":6,"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/posts\/132\/revisions"}],"predecessor-version":[{"id":145,"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/posts\/132\/revisions\/145"}],"wp:attachment":[{"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/media?parent=132"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/categories?post=132"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/tags?post=132"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}