{"id":78932,"date":"2020-06-04T10:00:10","date_gmt":"2020-06-04T04:30:10","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=78932"},"modified":"2020-06-04T10:00:10","modified_gmt":"2020-06-04T04:30:10","slug":"java-bubble-sort","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/java-bubble-sort\/","title":{"rendered":"Java Bubble Sort Working and Example"},"content":{"rendered":"<p>Sorting generally means to sort or order a particular array or collection of elements into a particular sequence i.e either in ascending order or in descending order.<\/p>\n<p>There are many kinds of Sorting techniques to sort a given array of numbers. In this article, we will learn the Bubble Sort technique in Java. It is one of the most used techniques for Sorting.<\/p>\n<p>We will discuss it with its working and also we will implement it in Java to sort the array in both ascending and descending orders. So, without wasting time, let\u2019s start discussing what Bubble Sort is.<\/p>\n<h3>What is a Bubble Sort?<\/h3>\n<p>Bubble Sort is one of the simplest sorting techniques in Java to sort the array elements.<\/p>\n<p>The idea is to traverse from the starting element to the last one by comparing the adjacent elements and swapping them if they are not in the specific order.<\/p>\n<p>It is called Bubble sort because, at the end of each iteration, the largest number sits at the bottom of the array just like the heaviest bubble settles down in a vessel. The swapping of elements continues until the array is sorted and no more swapping is required.<\/p>\n<p>We can also sort the elements in the descending order in which the smallest element goes at the end of the array in each iteration. This can only happen if we inverse the weight of the element.<\/p>\n<p>Some important points about the Bubble sort are:<\/p>\n<p><strong>1.<\/strong> The <strong>Worst and Average case complexity<\/strong> of Bubble Sort is\u00a0<strong>O(n2)<\/strong>, where n denotes the total number of elements in the array.<\/p>\n<p><strong>2.<\/strong> The <strong>Best case complexity<\/strong> of Bubble sort is <strong>O(n)<\/strong>, where n is the number of elements in the array. This case can happen only when the given array is already sorted.<\/p>\n<p><strong>3.<\/strong> The <strong>Auxiliary space<\/strong> consumed by the bubble sort algorithm is\u00a0<strong>O(1)<\/strong><\/p>\n<p><strong>4.<\/strong> The Bubble Sort is a type of <strong>in Place Sorting.<\/strong><\/p>\n<p><strong>5.<\/strong> Bubble sort is a <strong>Stable<\/strong> Algorithm.<\/p>\n<p><em><strong>Note:<\/strong> We can optimize the algorithm of Bubble sort and reduce our complexity to the order of \u201cn\u201d <strong>(O(n))<\/strong> by adding some extra lines of code to the original code. <\/em><\/p>\n<p><em>If the user entered a sorted array, so, rather than applying for all the passes we can just apply for a single pass and check whether any swap occurs during the whole pass. <\/em><\/p>\n<p><em>If there are no swaps occurring in the whole pass then we stop the algorithm and return the original array. By adding this piece of code we can ensure to enhance our performance of the algorithm and also reduce the time complexity.<\/em><\/p>\n<h3>Working of Bubble Sort in Java<\/h3>\n<p>Now, we will see how the Bubble Sort in Java works with the given array. We have an array and to sort it, there are 4 iterations after which we will get a sorted array.<\/p>\n<p>The following diagram illustrates the working of a Bubble sort<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/06\/Working-of-Bubble-Sort-in-Java.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-78991\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/06\/Working-of-Bubble-Sort-in-Java.jpg\" alt=\"Working of Bubble Sort in Java\" width=\"794\" height=\"491\" \/><\/a><\/p>\n<h3>Bubble Sort Program in Java to sort a given array in ascending order<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.bubblesort;\npublic class BubbleSortDemo {\n  static void bubbleAscending(int[] myarray) {\n    int n = myarray.length;\n    int temp = 0;\n    for (int i = 0; i &lt; n; i++) {\n      for (int j = 1; j &lt; (n - i); j++) {\n        if (myarray[j - 1] &gt; myarray[j]) {\n          \/\/Code to swap the elements\n          temp = myarray[j - 1];\n          myarray[j - 1] = myarray[j];\n          myarray[j] = temp;\n        }\n      }\n    }\n\n  }\n  public static void main(String[] args) {\n    int myarray[] = {\n      4,\n      15,\n      12,\n      21,\n      2,\n      25,\n      10,\n      18\n    };\n\n    System.out.println(\"Array on which we apply Bubble Sort: \");\n    for (int i = 0; i &lt; myarray.length; i++) {\n      System.out.print(myarray[i] + \" \");\n    }\n    System.out.println();\n\n    bubbleAscending(myarray); \/\/Applying Bubble sort to sort the Array  \n\n    System.out.println(\"Array after applying Bubble Sort: \");\n    for (int i = 0; i &lt; myarray.length; i++) {\n      System.out.print(myarray[i] + \" \");\n    }\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nArray on which we apply Bubble Sort: 4, 15, 12, 21, 2, 25, 10, 18<\/p>\n<p>Array after applying Bubble Sort: 2, 4, 10, 12, 15, 18, 21, 25<\/p>\n<h3>Java Bubble Sort Example to sort a given array in Descending order<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.bubblesort;\npublic class BubbleSortDemo {\n  static void bubbleDescending(int[] myarray) {\n    int n = myarray.length;\n    int temp = 0;\n    for (int i = 0; i &lt; n; i++) {\n      for (int j = 1; j &lt; (n - i); j++) {\n        if (myarray[j - 1] &lt; myarray[j]) {\n          \/\/Code to swap the elements\n          temp = myarray[j - 1];\n          myarray[j - 1] = myarray[j];\n          myarray[j] = temp;\n        }\n      }\n    }\n  }\n  public static void main(String[] args) {\n    int myarray[] = {\n      4,\n      15,\n      12,\n      21,\n      2,\n      25,\n      10,\n      18\n    };\n\n    System.out.println(\"Array on which we apply Bubble Sort: \");\n    for (int i = 0; i &lt; myarray.length; i++) {\n      System.out.print(myarray[i] + \" \");\n    }\n    System.out.println();\n\n    bubbleDescending(myarray); \/\/Applying Bubble sort to sort the Array  \n\n    System.out.println(\"Array after applying Bubble Sort: \");\n    for (int i = 0; i &lt; myarray.length; i++) {\n      System.out.print(myarray[i] + \" \");\n    }\n\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nArray on which we apply Bubble Sort: 4, 15, 12, 21, 2, 25, 10, 18<\/p>\n<p>Array after applying Bubble Sort: 25, 21, 18, 15, 12, 10, 4, 2<\/p>\n<h3>Use of Java Bubble Sort<\/h3>\n<p>As the Bubble Sort technique is the simplest sorting technique, it is often used in many areas of software technologies.<\/p>\n<p>For example, the Bubble Sort is very useful in the field of Computer graphics where it can be used to detect a very small error for example swap between two elements and fix the error with a linear complexity of 2n, where n is the number of elements in the array.<\/p>\n<h3>Advantages of Bubble Sort in Java<\/h3>\n<p>The advantages of bubble sort are:<\/p>\n<ul>\n<li>It is simple to write and easy to understand<\/li>\n<li>It takes only a few lines of code<\/li>\n<li>Bubble sort is an in-place sorting technique, therefore the data is in the memory, and therefore there is minimal memory overhead.<\/li>\n<\/ul>\n<h3>Disadvantages of Java Bubble Sort<\/h3>\n<p>There are also some drawbacks of bubble sort which are:<\/p>\n<ul>\n<li>It takes more amount of time to sort the array elements.<\/li>\n<li>The average time complexity increases with the increase in the number of elements of the array.<\/li>\n<\/ul>\n<h3>Conclusion<\/h3>\n<p>In this article, we studied what Bubble Sort is in Java and how we can use it to sort the array elements in a particular order. It is very easy to understand.<\/p>\n<p>But we can conclude that it works best with the small arrays and its performance degrades as the number of array elements grows.We learned to sort an array in ascending as well descending order with the help of a Java program.<\/p>\n<p>We can also increase the performance and efficiency of the bubble sort algorithm by adding a few lines of code to the original code. This article will surely help you become a master in the Bubble Sort technique in Java.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Sorting generally means to sort or order a particular array or collection of elements into a particular sequence i.e either in ascending order or in descending order. There are many kinds of Sorting techniques&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":78990,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[2766,2767,2768,2769,2770],"class_list":["post-78932","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-bubble-sort-algorithm-java","tag-bubble-sort-in-java","tag-bubble-sort-program-in-java","tag-java-bubble-sort","tag-java-bubble-sort-example"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java Bubble Sort Working and Example - TechVidvan<\/title>\n<meta name=\"description\" content=\"What is Bubble sort in java - Working of java bubble sort, its advantages and limitations ,sort numbers in ascending and descending order using bubble sort\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/java-bubble-sort\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Bubble Sort Working and Example - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"What is Bubble sort in java - Working of java bubble sort, its advantages and limitations ,sort numbers in ascending and descending order using bubble sort\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/java-bubble-sort\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-06-04T04:30:10+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Bubble-Sort-in-Java.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan 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":"Java Bubble Sort Working and Example - TechVidvan","description":"What is Bubble sort in java - Working of java bubble sort, its advantages and limitations ,sort numbers in ascending and descending order using bubble sort","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:\/\/techvidvan.com\/tutorials\/java-bubble-sort\/","og_locale":"en_US","og_type":"article","og_title":"Java Bubble Sort Working and Example - TechVidvan","og_description":"What is Bubble sort in java - Working of java bubble sort, its advantages and limitations ,sort numbers in ascending and descending order using bubble sort","og_url":"https:\/\/techvidvan.com\/tutorials\/java-bubble-sort\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-06-04T04:30:10+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Bubble-Sort-in-Java.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/java-bubble-sort\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-bubble-sort\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Java Bubble Sort Working and Example","datePublished":"2020-06-04T04:30:10+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-bubble-sort\/"},"wordCount":822,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-bubble-sort\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Bubble-Sort-in-Java.jpg","keywords":["bubble sort algorithm java","Bubble sort in Java","bubble sort program in java","Java Bubble Sort","java bubble sort example"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/java-bubble-sort\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/java-bubble-sort\/","url":"https:\/\/techvidvan.com\/tutorials\/java-bubble-sort\/","name":"Java Bubble Sort Working and Example - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-bubble-sort\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-bubble-sort\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Bubble-Sort-in-Java.jpg","datePublished":"2020-06-04T04:30:10+00:00","description":"What is Bubble sort in java - Working of java bubble sort, its advantages and limitations ,sort numbers in ascending and descending order using bubble sort","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-bubble-sort\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/java-bubble-sort\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/java-bubble-sort\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Bubble-Sort-in-Java.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Bubble-Sort-in-Java.jpg","width":802,"height":420,"caption":"Java bubble sort"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/java-bubble-sort\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Java Bubble Sort Working and Example"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/78932","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=78932"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/78932\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/78990"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=78932"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=78932"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=78932"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}