DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Recursive and Iterative Merge Sort Implementations

Chaker Nakhli user avatar by
Chaker Nakhli
·
Mar. 07, 12 · Interview
Like (0)
Save
Tweet
Share
53.79K Views

Join the DZone community and get the full member experience.

Join For Free

Curator's Note: In response to Stoimen Popov's Algorithm of the Week Post: Merge Sort, Chaker Nakhli pointed out that Stoimen only presented a recursive version of the merge sort algorithm. In this post, Chaker presents an iterative approach written in C#, but it can be easily converted to Java or any other language...


I find merge sort elegant and easy to implement and to understand for both iterative and recursive approaches. In this post I’ll share a quick (and probably dirty) iterative and recursive implementations of merge sort. Both versions share exactly the same merge operation. The implementation takes less than 30 lines of C#.

Recursive Merge Sort

public static T[] Recursive(T[] array, IComparer<T> comparer)
 {
     Recursive(array, 0, array.Length, comparer);
     return array;
 }
 
 private static void Recursive(T[] array, int start, int end, IComparer<T> comparer)
 {
     if (end - start <= 1) return;
     int middle = start + (end - start) / 2;
 
     Recursive(array, start, middle, comparer);
     Recursive(array, middle, end, comparer);
     Merge(array, start, middle, end, comparer);
 }

Iterative Merge Sort

public static T[] Iterative(T[] array, IComparer<T> comparer)
{
    for (int i = 1; i <= array.Length / 2 + 1; i *= 2)
    {
        for (int j = i; j < array.Length; j += 2 * i)
        {
            Merge(array, j - i, j, Math.Min(j + i, array.Length), comparer);
        }
    }
 
    return array;
}

Merge Function

The merge method below is used for both methods: recursive and iterative. It merges the two provided sub-arrays T[start, middle) and T[middle, end). The result of the merge cannot stored in the input array, it needs to be stored in a separate temporary array. This takes (end-start) memory space and will have a worst case space complexity O(n) where n is the size of the input array.

private static void Merge(T[] array, int start, int middle, int end, IComparer<T> comparer)
{
    T[] merge = new T[end-start];
    int l = 0, r = 0, i = 0;
    while (l < middle – start && r < end – middle)
    {
        merge[i++] = comparer.Compare(array[start + l], array[middle + r]) < 0
            ? array[start + l++]
            : array[middle + r++];
    }
 
    while (r < end – middle) merge[i++] = array[middle + r++];
 
    while (l < middle – start) merge[i++] = array[start + l++];
 
    Array.Copy(merge, 0, array, start, merge.Length);
}


Conclusion

As opposed to other in-place sorting algorithms, merge sort needs O(n) space to perform the merging step. On the other hand, it is a stable sort and it can be easily modified to implement external sorting for big data sets that do not fit in RAM.

Merge sort Implementation

Published at DZone with permission of Chaker Nakhli. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Why It Is Important To Have an Ownership as a DevOps Engineer
  • How to Quickly Build an Audio Editor With UI
  • Explainer: Building High Performing Data Product Platform
  • The Enterprise, the Database, the Problem, and the Solution

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: