{"id":4423,"date":"2024-08-05T13:00:56","date_gmt":"2024-08-05T13:00:56","guid":{"rendered":"https:\/\/msgprogramator.sk\/?p=4423"},"modified":"2026-02-17T11:40:42","modified_gmt":"2026-02-17T11:40:42","slug":"merge-sort","status":"publish","type":"post","link":"https:\/\/msgprogramator.sk\/en\/merge-sort\/","title":{"rendered":"Merge sort algorithm Java"},"content":{"rendered":"<p>Sorting algorithms are used to reorder the elements of an array or list in ascending or descending numerical or lexicographic order. Sorting is very important for the optimal performance of other algorithms that require sorted input data.<\/p>\n<p>There are many different sorting algorithms. The selection of an appropriate algorithm depends on factors such as the size and characteristics of the input data, available memory, and time and space complexity.<\/p>\n<p>To make your choice easier, in our series we will introduce the most well-known data sorting algorithms, explain their principles, advantages and disadvantages, and program them in Java.<\/p>\n<p>So far, we have discussed the following:<\/p>\n<ul>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/sorting-algorithms\/\" target=\"_blank\" rel=\"noopener\">Sorting algorithms<\/a>: Introduction to data sorting<\/li>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/bubble-sort\/\" target=\"_blank\" rel=\"noopener\">Bubble sort<\/a><\/li>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/comb-sort\/\" target=\"_blank\" rel=\"noopener\">Comb sort<\/a><\/li>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/big-o-notation\/\" target=\"_blank\" rel=\"noopener\">Big O notation<\/a><\/li>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/selection-sort\/\" target=\"_blank\" rel=\"noopener\">Selection sort<\/a><\/li>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/insertion-sort\/\" target=\"_blank\" rel=\"noopener\">Insertion sort<\/a><\/li>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/counting-sort\/\" target=\"_blank\" rel=\"noopener\">Counting sort<\/a><\/li>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/heap-sort\/\" target=\"_blank\" rel=\"noopener\">Heap sort<\/a><\/li>\n<\/ul>\n<p>Today we are going to look at <strong>merge sort<\/strong>.<\/p>\n<h2>Merge sort meaning<\/h2>\n<p>Merge sort is a very efficient stable sorting algorithm that was invented in 1945 by John von Neumann, one of the pioneers in the field of computer science. It uses the divide and conquer technique, the basic idea is that if we have a complex problem we try to break it down into smaller parts and solve those parts separately. The final solution is therefore the result of solving each of the smaller sub-problems. Such a decomposition of problems can then be perfectly parallelized and solved efficiently on modern multi-core processors.<\/p>\n<p>We divide the input data vector into several approximately equal parts. The most common version uses a 2-part partitioning, this is a binary merge, in the case of multiple parts it is a so-called <a href=\"https:\/\/en.wikipedia.org\/wiki\/K-way_merge_algorithm\" target=\"_blank\" rel=\"nofollow noopener\">K-way merge<\/a>. Let&#8217;s see how this technique can be used in data sorting.<\/p>\n<h2>How merge sort works<\/h2>\n<p>The input data is divided into approximately two equal parts, if the number of elements is odd, the first part has 1 more element. Each of these parts of the array is further divided in half and this is repeated until the part contains only one element. This uses a recursive call. An array with one element is considered to be sorted. Once the parts can no longer be split, the last two halves are taken and their elements are merged so that the resulting list remains sorted as well. This is repeated until the original data vector is received in sorted form. This is best understood with the example in the following figure.<\/p>\n<figure id=\"attachment_4042\" aria-describedby=\"caption-attachment-4042\" style=\"width: 890px\" class=\"wp-caption alignnone\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-4041 size-full\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/08\/algoritmus-merge-sortu-890-850.webp\" alt=\"Visual representation of the merge sort algorithm. The red part is the splitting phase and the green part is the merging phase. Source wikipedia \" width=\"890\" height=\"850\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/08\/algoritmus-merge-sortu-890-850.webp 890w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/08\/algoritmus-merge-sortu-890-850-300x287.webp 300w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/08\/algoritmus-merge-sortu-890-850-768x733.webp 768w\" sizes=\"auto, (max-width: 890px) 100vw, 890px\" \/><figcaption id=\"caption-attachment-4042\" class=\"wp-caption-text\">Visual representation of the merge sort algorithm. The red part is the splitting phase and the green part is the merging phase. Source wikipedia<\/figcaption><\/figure>\n<h2>Merge sort animation, visualization, gif<\/h2>\n<p>The merge sort animation looks like this:<\/p>\n<figure id=\"attachment_4045\" aria-describedby=\"caption-attachment-4045\" style=\"width: 344px\" class=\"wp-caption alignnone\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-4044 \" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/08\/Merge_sort_animation2.gif\" alt=\"CobaltBlue, CC BY-SA 4.0, via Wikimedia Commons\" width=\"344\" height=\"291\" \/><figcaption id=\"caption-attachment-4045\" class=\"wp-caption-text\">CobaltBlue, CC BY-SA 4.0, via Wikimedia Commons<\/figcaption><\/figure>\n<p>Source: commons.wikimedia.org\/wiki\/Category:Animations_of_sort_algorithms<\/p>\n<p>Visit <a href=\"https:\/\/www.toptal.com\/developers\/sorting-algorithms\" target=\"_blank\" rel=\"nofollow noopener\">Toptal <\/a> for interactive visualizations. There are 8 types of algorithms and you can also play the animation backwards.<\/p>\n<p>On <a href=\"https:\/\/www.hackerearth.com\/practice\/algorithms\/sorting\/merge-sort\/visualize\/\" target=\"_blank\" rel=\"nofollow noopener\"> this page<\/a> you can go through the steps of the algorithm to check the time taken by the algorithm.<\/p>\n<h2>Merge sort algorithm advantages<\/h2>\n<ul>\n<li>Stable algorithm<\/li>\n<li>Efficient even for huge data sets<\/li>\n<li>Can be easily parallelized to spread the computational load across multiple processors<\/li>\n<\/ul>\n<h2>Merge sort algorithm disadvantages<\/h2>\n<ul>\n<li>Additional memory space is required to store data when merging subarrays<\/li>\n<\/ul>\n<h2>Merge sort time complexity<\/h2>\n<table width=\"536\">\n<thead>\n<tr>\n<th rowspan=\"2\" width=\"94\"><strong>Algorithm<\/strong><\/th>\n<th rowspan=\"2\" width=\"84\"><strong>Method<\/strong><\/th>\n<th colspan=\"3\" width=\"208\"><strong>Time Complexity<\/strong><\/th>\n<th rowspan=\"2\" width=\"82\"><strong>Memory<\/strong><\/th>\n<th rowspan=\"2\" width=\"69\"><strong>Stable<\/strong><\/th>\n<\/tr>\n<tr>\n<th width=\"73\"><strong>worst<\/strong><\/th>\n<th width=\"63\"><strong>average<\/strong><\/th>\n<th width=\"71\"><strong>best<\/strong><\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td width=\"94\">Merge sort<\/td>\n<td width=\"84\">merging<\/td>\n<td width=\"73\">O(n log n)<\/td>\n<td width=\"63\">O(n log n)<\/td>\n<td width=\"71\">O(n log n)<\/td>\n<td width=\"82\">O(n)<\/td>\n<td width=\"69\">Yes<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2>Merge sort Java implementation<\/h2>\n<p>Now we will show the implementation of the merge sort algorithm in Java.<\/p>\n<p><strong><u>MergeSort.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package sorting;\n\npublic class MergeSort {\n    public void sort(int data[], int left, int right)\n    {\n        if (left &lt; right) {\n            \/\/ Find the cutting point\n            int middle = (left + right) \/ 2;\n            \/\/ Sort first and second part separately\n            sort(data, left, middle);\n            sort(data, middle + 1, right);\n            \/\/ Merge both sorted halves\n            merge(data, left, middle, right);\n        }\n    }\n\n    public void merge(int[] data, int left, int middle, int right) {\n        \/\/ Calculate sizes of left and right merge arrays\n        int leftPartSize = middle - left + 1;\n        int rightPartSize = right - middle;\n        \/\/ Create them\n        int[] leftPart = new int[leftPartSize];\n        int[] rightPart = new int[rightPartSize];\n        \/\/ Fill them\n        for (int i = 0; i &lt; leftPartSize; i++) {\n            leftPart[i] = data[left + i];\n        }\n        for (int j = 0; j &lt; rightPartSize; j++) {\n            rightPart[j] = data[middle + 1 + j];\n        }\n\n        System.out.print(&quot;L: &quot;);\n        printArray(leftPart);\n        System.out.print(&quot;+ R: &quot;);\n        printArray(rightPart);\n        System.out.print(&quot;=&gt; &quot;);\n\n        \/\/ k is index of merged array\n        int i = 0, j = 0, k = left;\n        while (i &lt; leftPartSize &amp;&amp; j &lt; rightPartSize) {\n            if (leftPart[i] &lt;= rightPart[j]) {\n                data[k++] = leftPart[i++];\n            }\n            else {\n                data[k++] = rightPart[j++];\n            }\n        }\n        \/\/ Copy any remaining elements\n        while (i &lt; leftPartSize) {\n            data[k++] = leftPart[i++];\n        }\n        while (j &lt; rightPartSize) {\n            data[k++] = rightPart[j++];\n        }\n\n        for (i = left; i &lt; k; i++)\n            System.out.print(data[i] + &quot; &quot;);\n        System.out.println();\n    }\n\n    \/\/ Function to print an array\n    public void printArray(int data[])\n    {\n        for (int i = 0; i &lt; data.length; i++)\n            System.out.print(data[i] + &quot; &quot;);\n        \/\/System.out.println();\n    }\n}<\/code><\/pre>\n<p><strong><u>Main.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">import sorting.MergeSort;\n\npublic class Main {\n    public static void main(String[] args) {\n        int dataToSort[] = { 6, 5, 4, 2, 3, 1, 7 };\n        MergeSort mergeSort = new MergeSort();\n        System.out.print(&quot;Input: &quot;);\n        mergeSort.printArray(dataToSort);\n        System.out.println(&quot;&quot;);\n        mergeSort.sort(dataToSort, 0, dataToSort.length - 1);\n        System.out.print(&quot;Sorted: &quot;);\n        mergeSort.printArray(dataToSort);\n    }\n}<\/code><\/pre>\n<p>The output of this merge sort Java example is:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"size-medium wp-image-4053\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/08\/vystup-z-prikladu-merge-sort-575-410-300x214.webp\" alt=\"Merge sort output from example\" width=\"300\" height=\"214\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/08\/vystup-z-prikladu-merge-sort-575-410-300x214.webp 300w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/08\/vystup-z-prikladu-merge-sort-575-410.webp 575w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/p>\n<p>We have prepared the files with the above example as code that you can run directly in Java. Download the <a href=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/08\/MergeSort.zip\" target=\"_blank\" rel=\"noopener\">Java <strong>MergeSort <\/strong> code<\/a> here.<\/p>\n<p>If you&#8217;re a <a href=\"https:\/\/msg-life.sk\/en\/jobs\/java-programmer-senior\/\" target=\"_blank\" rel=\"noopener\">Java developer<\/a> looking for a job, check out our <a href=\"https:\/\/msg-life.sk\/en\/benefits\/\" target=\"_blank\" rel=\"noopener\">employee benefits<\/a> and respond to our <a href=\"https:\/\/msg-life.sk\/en\/jobs\/\" target=\"_blank\" rel=\"noopener\">job offers<\/a>!<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article you will learn what merge sort is, its principle, advantages, disadvantages, visualization and example Java code.<\/p>\n","protected":false},"author":14,"featured_media":4048,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[57],"tags":[],"class_list":["post-4423","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java"],"acf":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/4423","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/comments?post=4423"}],"version-history":[{"count":7,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/4423\/revisions"}],"predecessor-version":[{"id":9726,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/4423\/revisions\/9726"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media\/4048"}],"wp:attachment":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media?parent=4423"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/categories?post=4423"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/tags?post=4423"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}