

{"id":18281,"date":"2018-06-12T04:00:55","date_gmt":"2018-06-12T04:00:55","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=18281"},"modified":"2026-05-22T17:15:54","modified_gmt":"2026-05-22T11:45:54","slug":"bubble-sort-in-java","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/bubble-sort-in-java\/","title":{"rendered":"Bubble Sort in Java &#8211; Learn How to Implement with Example!"},"content":{"rendered":"<p>Sorting is a technique used by programmers around the world to arrange a given set of data in either ascending or descending order. Sorting is an integral part of data structure and a concept that cannot be neglected by programmers. In this article, we will take a look at one such sorting method known as Bubble sort in java.<\/p>\n<h3>What is Bubble sort?<\/h3>\n<p>Bubble sort is a stable sorting algorithm. You might ask what a stable sort is; it basically means that if there are two elements in the data set that are the same, the order of the elements will be retained even after sorting.<\/p>\n<p>Bubble sort repeatedly checks all the elements and swaps them to either take the largest element to the end or bring the smallest element to the front. The mechanism of bubble sort remains the same, but the sorting might vary depending on the user\u2019s needs.<\/p>\n<h3>Why the name Bubble Sort?<\/h3>\n<p>The name given to this sort is very unique due to its unique feature. Bubble sort brings all the smaller elements to the top of the list and takes the largest element to the end of the list. We can say, just as bubbles float upwards as they are lighter than air, in bubble sort as well, the lighter elements move to the top. Hence the name Bubble Sort.<\/p>\n<h3>Bubble Sort Algorithm<\/h3>\n<p>Let us now see how Bubble sort works through a simple algorithm.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">Algo_BubbleSort(A, N)\r\nStep 1: Repeat for i in 0 to N\r\nStep 2: Repeat for j in 0 to N-i-1\r\nStep 3: Check If A[j] &gt; A[j+1] then\r\nStep 4: Swap A[j] and A[j+1]\r\nStep 5: End Inner Loop\r\nStep 6: End Outer Loop\r\nStep 7: End Process\r\n<\/pre>\n<h4>Dry Run of the above algorithm(Working Example):<\/h4>\n<p>Let us consider the following list: 3 4 1 2 6 8 7<br \/>\nWe will check only one full iteration in detail to understand the working of Bubble sort.<\/p>\n<p><strong>Iteration 1:<\/strong><br \/>\na. Compare 3 and 4, Since 3&lt;4, No swapping.<br \/>\nb. Compare 4 and 1, Since 4&gt;1, Swapping needed: 3 1 4 2 6 8 7<br \/>\nc. Compare 4 and 2, Since 4&gt;2, Swapping needed: 3 1 2 4 6 8 7<br \/>\nd. Compare 4 and 6, Since 4&lt;6, No swapping.<br \/>\ne. Compare 6 and 8, Since 6&lt;8, No swapping.<br \/>\nf. Compare 8 and 7, Since 8&gt;7, Swapping needed: 3 1 2 4 6 7 8<\/p>\n<p>This was just one iteration of the outer loop, this continues for N-1 times, where N is the size of the Array.<br \/>\nWe can see from the above example clearly, how the largest element, i.e. 8, gets swapped to the end of the array.<\/p>\n<p><strong>Implementing Bubble Sort to Arrange in Ascending Order:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.DataFlair.Bubblesort;\r\nclass bubble_sort\r\n{\r\n    public static void main()\r\n    {\r\n        int i,j,temp,n=7;\r\n        int array[]={3,4,1,2,6,8,7};\r\n        for(i=0;i&lt;n;i++)\r\n        {\r\n            for(j=0;j&lt;n-i-1;j++)\r\n            {\r\n                if(array[j]&gt;array[j+1])\r\n                {\r\n                    temp = array[j];\r\n                    array[j] = array[j+1];\r\n                    array[j+1] = temp;\r\n                }\r\n            }\r\n        }\r\n        System.out.println(\"The array after sorting is: \\n\");\r\n        for(i=0;i&lt;n;i++)\r\n        {\r\n            System.out.print(array[i]);\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">The array after sorting is:<br \/>\n1234678<\/div>\n<p><strong>Implementing Bubble Sort to Arrange in Descending Order:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.DataFlair.Bubblesort;\r\nclass bubble_sort\r\n{\r\n    public static void main()\r\n    {\r\n        int i,j,temp,n=8;\r\n        int array[]={1,2,3,4,5,6,7,8};\r\n        for(i=0;i&lt;n;i++)\r\n        {\r\n            for(j=0;j&lt;n-i-1;j++)\r\n            {\r\n                if(array[j]&lt;array[j+1])\r\n                {\r\n                    temp = array[j];\r\n                    array[j] = array[j+1];\r\n                    array[j+1] = temp;\r\n                }\r\n            }\r\n        }\r\n        System.out.println(\"The array after sorting is: \\n\");\r\n        for(i=0;i&lt;n;i++)\r\n        {\r\n            System.out.print(array[i]);\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">The array after sorting is:<br \/>\n87654321<\/div>\n<h3>Time and Space Complexity of Bubble Sort<\/h3>\n<ul>\n<li>The best-case time complexity of bubble sort is O(n)<\/li>\n<li>The Worst-Case time complexity of bubble sort is O(n^2)<\/li>\n<li>The Average Case time complexity of bubble sort is O(n^2)<\/li>\n<li>The Space Complexity of bubble sort is O(n)<\/li>\n<li>The Auxiliary Space Complexity of bubble sort is O(1)<\/li>\n<\/ul>\n<h3>Optimization of Bubble Sort<\/h3>\n<p><strong>Consider the following scenario:<\/strong><\/p>\n<p>The given array contains: 1 2 3 4 5 6 7 8<\/p>\n<p>We can see that the array is already sorted; we don\u2019t need to run the algorithm at all. But due to the mechanism of the algorithm, the algorithm will still execute N-1 times.<\/p>\n<p>Now, consider a scenario where the array is sorted after the first or second iteration; in that case, as well, the program will run N-1 times. This is a major issue with respect to time complexity. Let us see how we can fix the above program to get the optimal time complexity.<\/p>\n<h4>Optimized Program for Bubble Sort in Java:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.DataFlair.Bubblesort;\r\nclass bubble_sort\r\n{\r\n    public static void main()\r\n    {\r\n        int i,j,temp,n=8;\r\n        boolean flag= false;\r\n        int array[]={1,2,3,4,5,6,7,8};\r\n        for(i=0;i&lt;n;i++)\r\n        {\r\n            flag = false;\r\n            for(j=0;j&lt;n-i-1;j++)\r\n            {\r\n                if(array[j]&gt;array[j+1])\r\n                {\r\n                    flag=true;\r\n                    temp = array[j];\r\n                    array[j] = array[j+1];\r\n                    array[j+1] = temp;\r\n                }\r\n            }\r\n            if(flag==false)\r\n            {\r\n                System.out.println(\"The Array is Sorted\");\r\n                break;\r\n            }\r\n        }\r\n        System.out.println(\"The array after sorting is: \\n\");\r\n        for(i=0;i&lt;n;i++)\r\n        {\r\n            System.out.print(array[i]);\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">The Array is Sorted<br \/>\nThe array after sorting is:<br \/>\n12345678<\/div>\n<p>As we can see, by adding a flag variable, we can optimize the bubble sort technique. The flag variable basically checks if there are any swapping operations happening in the inner loop, and if there are no swapping operations, it means that the array is already sorted, and we break out of the loop. This process reduces the complexity of the program by far and prevents unnecessary looping.<\/p>\n<p><strong>Use of Bubble Sort<\/strong><\/p>\n<ul>\n<li>Bubble sort is a simple yet useful sorting technique; it can sort a given set of data in linear time complexity for best-case scenarios.<\/li>\n<li>It can be used in greedy algorithms like Kruskal\u2019s Algorithm to find the Minimal spanning tree in a graph.<\/li>\n<li>It can also be used in polygon filling algorithms to detect very small errors in linear time complexity of 2n.<\/li>\n<\/ul>\n<h3>Advantages of Bubble Sort in Java<\/h3>\n<p>1. Bubble sort is a basic sorting technique that requires a few lines of code and is very easy to understand.<\/p>\n<p>2. It doesn\u2019t use any complex algorithm techniques like Divide and Conquer or Divide and Conquer.<\/p>\n<p>3. It is a stable sort, and thus the element\u2019s memory location remains unchanged for equal value.<\/p>\n<p>4. Bubble sort is useful when you need to sort a smaller number of elements.<\/p>\n<h3>Disadvantages of Bubble Sort in Java<\/h3>\n<p>1. For the average or worst-case scenario, bubble sort has a polynomial-time complexity of n^2; thus, a data set with above a certain number of elements will take forever to calculate even on a supercomputer.<\/p>\n<p>2. Bubble sort works very slowly on modern CPUs. It writes in the memory way more than any other sorting technique and produces even more cache misses.<\/p>\n<p>3. The bubble sort does not utilize the CPU efficiently. As it sorts the elements one by one, the CPU is free most of the time.<\/p>\n<p>4. When it comes to sorting the large number of arrays, it fails to perform and takes much more time.<\/p>\n<p>5. As this algorithm has a slower performance speed, it is not used by most of the modern applications for solving complex problems.<\/p>\n<h3>Applications of Bubble Sort in Java<\/h3>\n<p>Despite its limitations, bubble sort can still be useful in certain scenarios. Here are a few examples:<\/p>\n<p><strong>1. Small Datasets:<\/strong> When dealing with very small datasets (fewer than 10 or 20 elements), bubble sort&#8217;s simplicity and ease of implementation can make it a suitable choice.<\/p>\n<p><strong>2. Educational Purposes:<\/strong> Due to its clear logic, bubble sort is often used as an introductory sorting algorithm in computer science courses. It helps students grasp the fundamental concepts of sorting before moving on to more complex algorithms.<\/p>\n<p><strong>3. Optimization Techniques:<\/strong> Bubble sort can be a building block for optimization techniques in other sorting algorithms. For instance, some sorting algorithms, like insertion sort, might utilize bubble sort for partially sorted arrays<\/p>\n<h3>Conclusion<\/h3>\n<p>Bubble sort is the most commonly used algorithm for sorting due to its simplicity. In this article, we discussed in detail how bubble sort is implemented and how to optimize the bubble sort algorithm. We also discussed the uses of bubble sort and also the advantages and disadvantages of this sorting technique.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Sorting is a technique used by programmers around the world to arrange a given set of data in either ascending or descending order. Sorting is an integral part of data structure and a concept&#46;&#46;&#46;<\/p>\n","protected":false},"author":5,"featured_media":99475,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[20804,7407,20805],"class_list":["post-18281","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-java-bubble-sort","tag-java-bubble-sort-tutorial","tag-java-bubble-sort-with-example"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Bubble Sort in Java - Learn How to Implement with Example! - DataFlair<\/title>\n<meta name=\"description\" content=\"Bubble sort in java is used to compare two adjcent element of an array. Learn how to implement this sorting algorithm with coding example\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/bubble-sort-in-java\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Bubble Sort in Java - Learn How to Implement with Example! - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Bubble sort in java is used to compare two adjcent element of an array. Learn how to implement this sorting algorithm with coding example\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/bubble-sort-in-java\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2018-06-12T04:00:55+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-05-22T11:45:54+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/06\/Bubble-Sort-Java.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Bubble Sort in Java - Learn How to Implement with Example! - DataFlair","description":"Bubble sort in java is used to compare two adjcent element of an array. Learn how to implement this sorting algorithm with coding example","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/bubble-sort-in-java\/","og_locale":"en_US","og_type":"article","og_title":"Bubble Sort in Java - Learn How to Implement with Example! - DataFlair","og_description":"Bubble sort in java is used to compare two adjcent element of an array. Learn how to implement this sorting algorithm with coding example","og_url":"https:\/\/data-flair.training\/blogs\/bubble-sort-in-java\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2018-06-12T04:00:55+00:00","article_modified_time":"2026-05-22T11:45:54+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/06\/Bubble-Sort-Java.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/bubble-sort-in-java\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/bubble-sort-in-java\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823"},"headline":"Bubble Sort in Java &#8211; Learn How to Implement with Example!","datePublished":"2018-06-12T04:00:55+00:00","dateModified":"2026-05-22T11:45:54+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/bubble-sort-in-java\/"},"wordCount":1080,"commentCount":2,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/bubble-sort-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/06\/Bubble-Sort-Java.jpg","keywords":["Java Bubble Sort","Java Bubble sort tutorial","Java Bubble Sort with Example"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/bubble-sort-in-java\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/bubble-sort-in-java\/","url":"https:\/\/data-flair.training\/blogs\/bubble-sort-in-java\/","name":"Bubble Sort in Java - Learn How to Implement with Example! - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/bubble-sort-in-java\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/bubble-sort-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/06\/Bubble-Sort-Java.jpg","datePublished":"2018-06-12T04:00:55+00:00","dateModified":"2026-05-22T11:45:54+00:00","description":"Bubble sort in java is used to compare two adjcent element of an array. Learn how to implement this sorting algorithm with coding example","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/bubble-sort-in-java\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/bubble-sort-in-java\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/bubble-sort-in-java\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/06\/Bubble-Sort-Java.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/06\/Bubble-Sort-Java.jpg","width":1200,"height":628,"caption":"Bubble Sort in Java"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/bubble-sort-in-java\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Java Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/java\/"},{"@type":"ListItem","position":3,"name":"Bubble Sort in Java &#8211; Learn How to Implement with Example!"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam1\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/18281","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=18281"}],"version-history":[{"count":19,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/18281\/revisions"}],"predecessor-version":[{"id":148415,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/18281\/revisions\/148415"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/99475"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=18281"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=18281"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=18281"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}