Algorithm note (6) Merge and sort

Source: Internet
Author: User

Today, I am mainly studying the Merge Sorting Algorithm Based on the divide and conquer idea. This is a typical application of divide and conquer law. If you don't talk nonsense, Let's go straight to the question below.

Overview:

The two ordered arrays are merged into a larger ordered array, which we call merge. According to this operation, people have invented a simple recursive Sorting Algorithm: Merge Sorting.

Merge Sorting is most attractive because it can ensure that the time required for sorting arrays of any length of N is proportional to nlogn; its main drawback is that the memory space needed to be occupied is proportional to n.

Analysis:
One of the simplest ways to implement merging is to merge two different ordered arrays into the third array. The implementation method is very simple, create an appropriate array and add the elements in the two arrays from small to large to this array. However, the problem is that, when sorting large arrays, it is necessary to merge multiple times and create new Arrays for each merge, which will undoubtedly bring about a huge problem. Therefore, we need a method that can achieve in-situ merging, so that we can first sort the left side, then sort the right side, and then move elements in the array without extra memory space, we will describe this method in the implementation section.

 

Implementation:
In-situ merge method:

private static void merge(IComparable[] a, int lo, int mid, int hi)        {            int i = lo, j = mid + 1;            for (int k = lo; k <= hi; k++)                aux[k] = a[k];            for (int k = lo; k <= hi; k++)            {                if (i > mid)                       a[k] = aux[j++];                else if (j > hi)                   a[k] = aux[i++];                else if (less(aux[j], aux[i]))     a[k] = aux[j++];                else                               a[k] = aux[i++];            }        }

The following are two different final implementation algorithms. They are typical examples of the Division idea in the application of efficient algorithm design.

Top-down merge implementation:

public class Merge    {        private static IComparable[] aux;        public static void sort(IComparable[] a)        {            aux = new IComparable[a.Length];            sort(a, 0, a.Length - 1);        }        private static void sort(IComparable[] a,int lo,int hi)        {            if (hi <= lo) return;            int mid = lo + (hi - lo) / 2;            sort(a, lo, mid);            sort(a, mid + 1, hi);            merge(a, lo, mid, hi);        }        public static bool less(IComparable v, IComparable w)        {            return v.CompareTo(w) < 0;        }        public static void exch(IComparable[] a, int i, int j)        {            IComparable temp = a[i];            a[i] = a[j];            a[j] = temp;        }        public static void show(IComparable[] a)        {             int N=a.Length;            for (int i = 0; i < N; i++)                Console.WriteLine(a[i]);        }        private static void merge(IComparable[] a, int lo, int mid, int hi)        {            int i = lo, j = mid + 1;            for (int k = lo; k <= hi; k++)                aux[k] = a[k];            for (int k = lo; k <= hi; k++)            {                if (i > mid)                       a[k] = aux[j++];                else if (j > hi)                   a[k] = aux[i++];                else if (less(aux[j], aux[i]))     a[k] = aux[j++];                else                               a[k] = aux[i++];            }        }        public static void test(int size)        {            DateTime startDate = DateTime.Now;            Data[] data = new Data[size];            Random rd = new Random();            for (int i = 0; i < size; i++)            {                data[i] = new Data { value = rd.Next(10000000) };            }            Console.WriteLine("After sort:");            Merge.sort(data);            DateTime endDate = DateTime.Now;            double time = (endDate.Hour - startDate.Hour) * 3600 * 1000 + (endDate.Minute - startDate.Minute) * 60 * 1000 + (endDate.Second - startDate.Second) * 1000 + (endDate.Millisecond - startDate.Millisecond);            if (time > 1000) time /= 1000;            Console.WriteLine("time:" + time);        }        public static void Main(string[] args)        {            test(1000);        }    }

 

Bottom-up Merge Sorting:

 public static void sort(IComparable[] a)        {            int N = a.Length;            aux = new IComparable[N];            for(int sz=1;sz<N;sz++)                for(int lo=0;lo<N-sz;lo+=sz+sz)                    merge(a,lo,lo+sz-1,System.Math.Min(lo+sz+sz-1,N-1));            //sort(a, 0, a.Length - 1);        }

It is natural to use top-down or bottom-up algorithms to implement Sub-governance. Description of the implementation of the Merge Sorting Algorithm. If you can solve a problem in one way, try another method. The bottom-up method is suitable for organizing the structure of the linked list, and can sort the linked list in situ.

 

In fact, I do not have a deep understanding of the merge algorithm, but I am amazed at the degree of code refinement and execution speed. I sorted it with Hill and.. Net encapsulated array. after sort () is compared and tested, it is found that the Merge Sorting speed is the closest to the native API speed. It takes only 10000000 s to sort 15.672 random numbers, and 53.937 s to sort by hill, the native method requires 15.062s. if you have any good articles, please recommend them to me. I am very grateful for ing.

Algorithm note (6) Merge and sort

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.