## Merge Sort

### November 10, 2009

It is awkward to sort arrays by merge sort, since it requires two arrays, an input array and an output array; merge sort is used far more often to sort linked lists, as in the Standard Prelude. We begin with a function that merges two sub-arrays, `left` through `middle` and `middle + 1` through `right`, from an input array into the positions `left` through `right` in an output array:

```function merge(A,left,middle,right,    B,i,j,k) {     i = left; j = middle + 1     while (i <= middle && j <= right)         if (A[i] <= A[j]) B[++k] = A[i++]         else B[++k] = A[j++]     while (i <= middle)         B[++k] = A[i++]     while (j <= right)         B[++k] = A[j++]     for (k = left; k <= right; k++) {         A[k] = B[k]; delete B[k] } }```

Here `i` indexes the first sub-array, `j` indexes the second sub-array, and `k` indexes the output array; we take advantage of Awk’s implicit initialization for `k = 0`. The first `while` loop runs until one of the sequences ends, the second and third `while` loops pick up the remainders of the runs, and the fourth `while` loop copies the output array back to the input array. Notice that we broke our convention, using less-than-or-equal instead of less-than to compare array elements; doing so allows our sort to be stable, with equal elements appearing in the output in the same order as the input.

Given `merge`, the actual `sort` function splits the array in two, sorts the two halves recursively, then merges them together:

```function mergesort(A,left,right,    middle) {     if (left < right) {         middle = int((left + right) / 2)         mergesort(A, left, middle)         mergesort(A, middle + 1, right)         merge(A, left, middle, right) } }```

`function sort(A,n) { mergesort(A, 1, n) }`

``` If you like, you can move the merge inline and eliminate recursion; l1 and l2 index the lower bounds of the two sub-arrays, u1 and u2 index the upper bounds of the two sub-arrays, k indexes the output array, and g is the gap between the two sub-arrays, which doubles at each pass: function sort(A,n,    l1,l2,u1,u2,k,g,B) {     for (g = 1; g < n; g *= 2) {         k = 0         for (l1 = 1; l1 + g <= n; l1 = u2 + 1) {             l2 = l1 + g; u1 = l2 - 1             u2 = l2 + g - 1; if (u2 > n) u2 = n             while (l1 <= u1 && l2 <= u2)                 if (A[l1] <= A[l2])                     B[++k] = A[l1++]                 else B[++k] = A[l2++]             while (l1 <= u1)                 B[++k] = A[l1++]             while (l2 <= u2)                 B[++k] = A[l2++] }         while (k < n)             B[++k] = A[l1++]         for (k = 1; k <= n; k++)             A[k] = B[k] } } All of the code, including the test suite of the prior exercise, is collected at http://programmingpraxis.codepad.org/Wk6rsu1Z, but you can't run it because codepad doesn't provide an Awk interpreter. (function(g){g.__ATA.initAd({sectionId:26942, width:300, height:250});})(window); Like this:Like Loading... Related Pages: 1 2 ```
``` Posted by programmingpraxis Filed in Exercises 2 Comments » ```
``` 2 Responses to “Merge Sort” r. clayton said November 20, 2009 at 2:48 AM An idiotically cumbersome Java mergesort implementation. The private mergesort returns a pointer to the fully sorted (unsegmented) array. Vikas Tandi said April 30, 2011 at 8:36 AM My implementation in C #define MODCOPY(x,y) (((x) < 0) ? ((x) = (-y)) : ((x) = (y))) typedef struct ElementNode { int key; int link; }element; static void mergesort_imp(element arr[], int left, int right); static void swap(element arr[], int i, int j); void mergesort(element arr[], int left, int right) { int p, q, k; /* arrange the links in sorted order */ mergesort_imp(arr, left, right); /* sort the records in-place according to the links */ p = left-1; k = left; while(arr[p].link) { if(p < k) { p = arr[p].link; continue; } swap(arr, k, p); q = arr[k].link; arr[k].link = p; p = q; k++; } } /* arr[left-1] and arr[right+1] are two artificial nodes at the start and the end of list. A negative link denotes the end of a sublist known to be ordered; a zero link indicates the end of the entire list */ static void mergesort_imp(element arr[], int left, int right) { int i; int s, t , p, q; /* prepare two lists */ arr[left-1].link = left; arr[right+1].link = left+1; /* initially the file is assumed to be unordered, so setting all links to negative value */ for(i = left; i < (right-1); i++) arr[i].link = -(i+2); arr[right-1].link = 0; arr[right].link = 0; /* we have created two lists out of which one list contain all odd positioned elements and other list contain all even positioned elements */ /* main loop */ for(;;) { /* begin new pass */ s = left-1; t = right+1; p = arr[s].link; q = arr[right+1].link; if(q == 0) /* terminate */ break; for(;;) { /* compare keys */ if(arr[p].key > arr[q].key) { MODCOPY(arr[s].link, q); s = q; q = arr[q].link; if(q <= 0) { arr[s].link = p; s = t; do { t = p; p = arr[p].link; } while(p > 0); p = -p; q = -q; } } else { MODCOPY(arr[s].link, p); s = p; p = arr[p].link; if(p <= 0) { arr[s].link = q; s = t; do { t = q; q = arr[q].link; } while(q > 0); p = -p; q = -q; } } if(q == 0) break; } MODCOPY(arr[s].link, p); MODCOPY(arr[t].link, 0); } } static void swap(element arr[], int i, int j) { element temp; temp.key = arr[i].key; temp.link = arr[i].link; arr[i].key = arr[j].key; arr[i].link = arr[j].link; arr[j].key = temp.key; arr[j].link = temp.link; } Leave a Reply Enter your comment here... Fill in your details below or click an icon to log in: Email (required) (Address never made public) Name (required) Website You are commenting using your WordPress.com account. ( Log Out / Change ) You are commenting using your Twitter account. ( Log Out / Change ) You are commenting using your Facebook account. ( Log Out / Change ) You are commenting using your Google+ account. ( Log Out / Change ) Cancel Connecting to %s var highlander_expando_javascript = function(){ var input = document.createElement( 'input' ), comment = jQuery( '#comment' ); if ( 'placeholder' in input ) { comment.attr( 'placeholder', jQuery( '.comment-textarea label' ).remove().text() ); } // Expando Mode: start small, then auto-resize on first click + text length jQuery( '#comment-form-identity' ).hide(); jQuery( '#comment-form-subscribe' ).hide(); jQuery( '#commentform .form-submit' ).hide(); comment.css( { 'height':'10px' } ).one( 'focus', function() { var timer = setInterval( HighlanderComments.resizeCallback, 10 ) jQuery( this ).animate( { 'height': HighlanderComments.initialHeight } ).delay( 100 ).queue( function(n) { clearInterval( timer ); HighlanderComments.resizeCallback(); n(); } ); jQuery( '#comment-form-identity' ).slideDown(); jQuery( '#comment-form-subscribe' ).slideDown(); jQuery( '#commentform .form-submit' ).slideDown(); }); } jQuery(document).ready( highlander_expando_javascript ); Notify me of new comments via email. Notify me of new posts via email. ```
``` Categories Administrivia Exercises Archives November 2015 October 2015 September 2015 August 2015 July 2015 June 2015 May 2015 April 2015 March 2015 February 2015 January 2015 December 2014 November 2014 October 2014 September 2014 August 2014 July 2014 June 2014 May 2014 April 2014 March 2014 February 2014 January 2014 December 2013 November 2013 October 2013 September 2013 August 2013 July 2013 June 2013 May 2013 April 2013 March 2013 February 2013 January 2013 December 2012 November 2012 October 2012 September 2012 August 2012 July 2012 June 2012 May 2012 April 2012 March 2012 February 2012 January 2012 December 2011 November 2011 October 2011 September 2011 August 2011 July 2011 June 2011 May 2011 April 2011 March 2011 February 2011 January 2011 December 2010 November 2010 October 2010 September 2010 August 2010 July 2010 June 2010 May 2010 April 2010 March 2010 February 2010 January 2010 December 2009 November 2009 October 2009 September 2009 August 2009 July 2009 June 2009 May 2009 April 2009 March 2009 February 2009 November 2009 S M T W T F S « Oct   Dec » 1234567 891011121314 15161718192021 22232425262728 2930   Archives November 2015 October 2015 September 2015 August 2015 July 2015 June 2015 May 2015 April 2015 March 2015 February 2015 January 2015 December 2014 November 2014 October 2014 September 2014 August 2014 July 2014 June 2014 May 2014 April 2014 March 2014 February 2014 January 2014 December 2013 November 2013 October 2013 September 2013 August 2013 July 2013 June 2013 May 2013 April 2013 March 2013 February 2013 January 2013 December 2012 November 2012 October 2012 September 2012 August 2012 July 2012 June 2012 May 2012 April 2012 March 2012 February 2012 January 2012 December 2011 November 2011 October 2011 September 2011 August 2011 July 2011 June 2011 May 2011 April 2011 March 2011 February 2011 January 2011 December 2010 November 2010 October 2010 September 2010 August 2010 July 2010 June 2010 May 2010 April 2010 March 2010 February 2010 January 2010 December 2009 November 2009 October 2009 September 2009 August 2009 July 2009 June 2009 May 2009 April 2009 March 2009 February 2009 Blogroll WordPress.com WordPress.org ```
``` The Ambiru Theme. Blog at WordPress.com. /* <![CDATA[ */ var HighlanderComments = {"loggingInText":"Logging In\u2026","submittingText":"Posting Comment\u2026","postCommentText":"Post Comment","connectingToText":"Connecting to %s","commentingAsText":"%1\$s: You are commenting using your %2\$s account.","logoutText":"Log Out","loginText":"Log In","connectURL":"https:\/\/programmingpraxis.wordpress.com\/public.api\/connect\/?action=request","logoutURL":"https:\/\/programmingpraxis.wordpress.com\/wp-login.php?action=logout&_wpnonce=88916f3176","homeURL":"http:\/\/programmingpraxis.com\/","postID":"1602","gravDefault":"blank","enterACommentError":"Please enter a comment","enterEmailError":"Please enter your email address here","invalidEmailError":"Invalid email address","enterAuthorError":"Please enter your name here","gravatarFromEmail":"This picture will show whenever you leave a comment. Click to customize it.","logInToExternalAccount":"Log in to use details from one of these accounts.","change":"Change","changeAccount":"Change Account","comment_registration":"","userIsLoggedIn":"","isJetpack":"0","text_direction":"ltr"}; /* ]]> */ Follow Follow “Programming Praxis” Get every new post delivered to your Inbox. Join 701 other followers Build a website with WordPress.com %d bloggers like this: //<![CDATA[ var jetpackLikesWidgetQueue = []; var jetpackLikesWidgetBatch = []; var jetpackLikesMasterReady = false; function JetpackLikespostMessage( message, target ) { if ( "string" === typeof message ){ try{ message = JSON.parse( message ); } catch(e) { return; } } pm( { target: target, type: 'likesMessage', data: message, origin: '*' } ); } function JetpackLikesBatchHandler() { var requests = []; jQuery( 'div.jetpack-likes-widget-unloaded' ).each( function( i ) { if ( jetpackLikesWidgetBatch.indexOf( this.id ) > -1 ) return; jetpackLikesWidgetBatch.push( this.id ); var regex = /like-(post|comment)-wrapper-(\d+)-(\d+)-(\w+)/; var match = regex.exec( this.id ); if ( ! match || match.length != 5 ) return; var info = { blog_id: match[2], width: this.width }; if ( 'post' == match[1] ) { info.post_id = match[3]; } else if ( 'comment' == match[1] ) { info.comment_id = match[3]; } info.obj_id = match[4]; requests.push( info ); }); if ( requests.length > 0 ) { JetpackLikespostMessage( { event: 'initialBatch', requests: requests }, window.frames['likes-master'] ); } } function JetpackLikesMessageListener( event ) { if ( "undefined" == typeof event.event ) return; if ( 'masterReady' == event.event ) { jQuery( document ).ready( function() { jetpackLikesMasterReady = true; var stylesData = { event: 'injectStyles' }; if ( jQuery( 'iframe.admin-bar-likes-widget' ).length > 0 ) { JetpackLikespostMessage( { event: 'adminBarEnabled' }, window.frames[ 'likes-master' ] ); stylesData.adminBarStyles = { background: jQuery( '#wpadminbar .quicklinks li#wp-admin-bar-wpl-like > a' ).css( 'background' ), isRtl: ( 'rtl' == jQuery( '#wpadminbar' ).css( 'direction' ) ) }; } if ( !window.addEventListener ) jQuery( '#wp-admin-bar-admin-bar-likes-widget' ).hide(); stylesData.textStyles = { color: jQuery( '.sd-text-color').css( 'color' ), fontFamily: jQuery( '.sd-text-color' ).css( 'font-family' ), fontSize: jQuery( '.sd-text-color' ).css( 'font-size' ), direction: jQuery( '.sd-text-color' ).css( 'direction' ), fontWeight: jQuery( '.sd-text-color' ).css( 'font-weight' ), fontStyle: jQuery( '.sd-text-color' ).css( 'font-style' ), textDecoration: jQuery( '.sd-text-color' ).css('text-decoration') }; stylesData.linkStyles = { color: jQuery( '.sd-link-color' ).css('color'), fontFamily: jQuery( '.sd-link-color' ).css('font-family'), fontSize: jQuery( '.sd-link-color' ).css('font-size'), textDecoration: jQuery( '.sd-link-color' ).css('text-decoration'), fontWeight: jQuery( '.sd-link-color' ).css( 'font-weight' ), fontStyle: jQuery( '.sd-link-color' ).css( 'font-style' ) }; JetpackLikespostMessage( stylesData, window.frames[ 'likes-master' ] ); JetpackLikesBatchHandler(); jQuery( document ).on( 'inview', 'div.jetpack-likes-widget-unloaded', function() { jetpackLikesWidgetQueue.push( this.id ); }); }); } if ( 'showLikeWidget' == event.event ) { jQuery( '#' + event.id + ' .post-likes-widget-placeholder' ).fadeOut( 'fast', function() { jQuery( '#' + event.id + ' .post-likes-widget' ).fadeIn( 'fast', function() { JetpackLikespostMessage( { event: 'likeWidgetDisplayed', blog_id: event.blog_id, post_id: event.post_id, obj_id: event.obj_id }, window.frames['likes-master'] ); }); }); } if ( 'clickReblogFlair' == event.event ) { wpcom_reblog.toggle_reblog_box_flair( event.obj_id ); } if ( 'showOtherGravatars' == event.event ) { var \$container = jQuery( '#likes-other-gravatars' ); var \$list = \$container.find( 'ul' ); \$container.hide(); \$list.html( '' ); \$container.find( '.likes-text span' ).text( event.total ); jQuery.each( event.likers, function( i, liker ) { \$list.append( '<li class="' + liker.css_class + '"><a href="' + liker.profile_URL + '" class="wpl-liker" rel="nofollow" target="_parent"><img src="' + liker.avatar_URL + '" alt="' + liker.name + '" width="30" height="30" style="padding-right: 3px;" /></a></li>'); } ); var offset = jQuery( "[name='" + event.parent + "']" ).offset(); \$container.css( 'left', offset.left + event.position.left - 10 + 'px' ); \$container.css( 'top', offset.top + event.position.top - 33 + 'px' ); var rowLength = Math.floor( event.width / 37 ); var height = ( Math.ceil( event.likers.length / rowLength ) * 37 ) + 13; if ( height > 204 ) { height = 204; } \$container.css( 'height', height + 'px' ); \$container.css( 'width', rowLength * 37 - 7 + 'px' ); \$list.css( 'width', rowLength * 37 + 'px' ); \$container.fadeIn( 'slow' ); var scrollbarWidth = \$list[0].offsetWidth - \$list[0].clientWidth; if ( scrollbarWidth > 0 ) { \$container.width( \$container.width() + scrollbarWidth ); \$list.width( \$list.width() + scrollbarWidth ); } } } pm.bind( 'likesMessage', function(e) { JetpackLikesMessageListener(e); } ); jQuery( document ).click( function( e ) { var \$container = jQuery( '#likes-other-gravatars' ); if ( \$container.has( e.target ).length === 0 ) { \$container.fadeOut( 'slow' ); } }); function JetpackLikesWidgetQueueHandler() { var wrapperID; if ( ! jetpackLikesMasterReady ) { setTimeout( JetpackLikesWidgetQueueHandler, 500 ); return; } if ( jetpackLikesWidgetQueue.length > 0 ) { // We may have a widget that needs creating now var found = false; while( jetpackLikesWidgetQueue.length > 0 ) { // Grab the first member of the queue that isn't already loading. wrapperID = jetpackLikesWidgetQueue.splice( 0, 1 )[0]; if ( jQuery( '#' + wrapperID ).hasClass( 'jetpack-likes-widget-unloaded' ) ) { found = true; break; } } if ( ! found ) { setTimeout( JetpackLikesWidgetQueueHandler, 500 ); return; } } else if ( jQuery( 'div.jetpack-likes-widget-unloaded' ).length > 0 ) { // Grab any unloaded widgets for a batch request JetpackLikesBatchHandler(); // Get the next unloaded widget wrapperID = jQuery( 'div.jetpack-likes-widget-unloaded' ).first()[0].id; if ( ! wrapperID ) { // Everything is currently loaded setTimeout( JetpackLikesWidgetQueueHandler, 500 ); return; } } if ( 'undefined' === typeof wrapperID ) { setTimeout( JetpackLikesWidgetQueueHandler, 500 ); return; } var \$wrapper = jQuery( '#' + wrapperID ); \$wrapper.find( 'iframe' ).remove(); if ( \$wrapper.hasClass( 'slim-likes-widget' ) ) { \$wrapper.find( '.post-likes-widget-placeholder' ).after( "<iframe class='post-likes-widget jetpack-likes-widget' name='" + \$wrapper.data( 'name' ) + "' height='22px' width='68px' frameBorder='0' scrolling='no' src='" + \$wrapper.data( 'src' ) + "'></iframe>" ); } else { \$wrapper.find( '.post-likes-widget-placeholder' ).after( "<iframe class='post-likes-widget jetpack-likes-widget' name='" + \$wrapper.data( 'name' ) + "' height='55px' width='100%' frameBorder='0' src='" + \$wrapper.data( 'src' ) + "'></iframe>" ); } \$wrapper.removeClass( 'jetpack-likes-widget-unloaded' ).addClass( 'jetpack-likes-widget-loading' ); \$wrapper.find( 'iframe' ).load( function( e ) { var \$iframe = jQuery( e.target ); \$wrapper.removeClass( 'jetpack-likes-widget-loading' ).addClass( 'jetpack-likes-widget-loaded' ); JetpackLikespostMessage( { event: 'loadLikeWidget', name: \$iframe.attr( 'name' ), width: \$iframe.width() }, window.frames[ 'likes-master' ] ); if ( \$wrapper.hasClass( 'slim-likes-widget' ) ) { \$wrapper.find( 'iframe' ).Jetpack( 'resizeable' ); } }); setTimeout( JetpackLikesWidgetQueueHandler, 250 ); } JetpackLikesWidgetQueueHandler(); //]]> (function(){ var corecss = document.createElement('link'); var themecss = document.createElement('link'); var corecssurl = "http://s0.wp.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/styles/shCore.css?m=1422342134g&amp;ver=3.0.9b"; if ( corecss.setAttribute ) { corecss.setAttribute( "rel", "stylesheet" ); corecss.setAttribute( "type", "text/css" ); corecss.setAttribute( "href", corecssurl ); } else { corecss.rel = "stylesheet"; corecss.href = corecssurl; } document.getElementsByTagName("head")[0].insertBefore( corecss, document.getElementById("syntaxhighlighteranchor") ); var themecssurl = "http://s0.wp.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/styles/shThemeDefault.css?m=1363304414g&amp;ver=3.0.9b"; if ( themecss.setAttribute ) { themecss.setAttribute( "rel", "stylesheet" ); themecss.setAttribute( "type", "text/css" ); themecss.setAttribute( "href", themecssurl ); } else { themecss.rel = "stylesheet"; themecss.href = themecssurl; } //document.getElementById("syntaxhighlighteranchor").appendChild(themecss); document.getElementsByTagName("head")[0].insertBefore( themecss, document.getElementById("syntaxhighlighteranchor") ); })(); SyntaxHighlighter.config.strings.expandSource = '+ expand source'; SyntaxHighlighter.config.strings.help = '?'; SyntaxHighlighter.config.strings.alert = 'SyntaxHighlighter\n\n'; SyntaxHighlighter.config.strings.noBrush = 'Can\'t find brush for: '; SyntaxHighlighter.config.strings.brushNotHtmlScript = 'Brush wasn\'t configured for html-script option: '; SyntaxHighlighter.defaults['pad-line-numbers'] = false; SyntaxHighlighter.defaults['toolbar'] = false; SyntaxHighlighter.all(); // <![CDATA[ (function() { try{ if ( window.external &&'msIsSiteMode' in window.external) { if (window.external.msIsSiteMode()) { var jl = document.createElement('script'); jl.type='text/javascript'; jl.async=true; jl.src='/wp-content/plugins/ie-sitemode/custom-jumplist.php'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(jl, s); } } }catch(e){} })(); // ]]> _tkq = window._tkq || []; _stq = window._stq || []; _tkq.push(['storeContext', {'blog_id':'6649073','blog_tz':'0','user_lang':'en','blog_lang':'en','user_id':'0'}]); _stq.push(['view', {'blog':'6649073','v':'wpcom','tz':'0','user_id':'0','post':'1602','subd':'programmingpraxis'}]); _stq.push(['extra', {'crypt':'UE5XaGUuOTlwaD85flAmcm1mcmZsaDhkV11YdWtpP0NsWnVkPS9sL0ViLndld3AlSGN8YmRCSmtFZUxRR1lZc2ZadVg3cTBuL0VLL1ZwbmhsV0hlUFdwMm1rVGptMmJ8Wj1yP2hVWGdYfDVDRDJDW1ZRaG1uRkE2NjBRUnFSLiVELk5jSDJzYWQ1XWZnTUMtWDgrWHd4JmtvTmUtdjFJLXZ2c2Y5cVphRkxZLU9QMSxyeVFXdjVCQXY/ZG84SX5EdkdEZ1R0TWxLcHhoLWlnbk45aVo/Mlp4MDQufE5RUmlFTFFmUStmTmIzSHRxYSsmdGJkUnZILC9kX2Mvdyw2S2pQTlRwX3lGWUtQTWk3OVN5dS4/P3BOa1JGb2xRSTk9XzVoaA=='}]); _stq.push([ 'clickTrackerInit', '6649073', '1602' ]); if ( 'object' === typeof wpcom_mobile_user_agent_info ) { wpcom_mobile_user_agent_info.init(); var mobileStatsQueryString = ""; if( false !== wpcom_mobile_user_agent_info.matchedPlatformName ) mobileStatsQueryString += "&x_" + 'mobile_platforms' + '=' + wpcom_mobile_user_agent_info.matchedPlatformName; if( false !== wpcom_mobile_user_agent_info.matchedUserAgentName ) mobileStatsQueryString += "&x_" + 'mobile_devices' + '=' + wpcom_mobile_user_agent_info.matchedUserAgentName; if( wpcom_mobile_user_agent_info.isIPad() ) mobileStatsQueryString += "&x_" + 'ipad_views' + '=' + 'views'; if( "" != mobileStatsQueryString ) { new Image().src = document.location.protocol + '//pixel.wp.com/g.gif?v=wpcom-no-pv' + mobileStatsQueryString + '&baba=' + Math.random(); } } ```