Algorithm backup ---- Merge Sort(归并排序算法)

  Merge sort is an O(n log n) comparison-based sorting algorithm. In most implementations it is stable, meaning that it preserves the input order of equal elements in the sorted output. It is an example of the devide and conquer algorithmic paradigm.

  Conceptually, a merge sort works as follows:

  1. If the list is of length 0 or 1, then it is already sorted. Otherwise:

  2. Divide the unsorted list into two sublists of about half the size.

  3. Sort each sublist recursively by re-applying merge sort.

  4. Merge the two sublists back into one sorted list.

  Merge sort incorporates two main ideas to improve its runtime:

  1. A small list will take fewer steps to sort than a large list.

  2. Fewer steps are required to construct a sorted list from two sorted lists than two unsorted lists. For example, you only have to traverse each list once if they're already sorted.

  Below is the implementation using C#:

/// <summary>
/// Merge sort algorithm
/// </summary>
/// <param name="numbers">numbers to be sorted</param>
/// <param name="left">start subscript</param>
/// <param name="right">end subscript</param>
public static void MergeSort(int[] numbers, int left, int right)
{
    
if (left < right)
    {
        
int mid = (left + right) / 2;
        MergeSort(numbers, left, mid);
        MergeSort(numbers, mid 
+ 1, right);
        Merge(numbers, left, mid, right);
    }
}
/// <summary>
/// Merge two sorted parts
/// </summary>
/// <param name="numbers"></param>
/// <param name="first">start subscript</param>
/// <param name="mid">middle subscript</param>
/// <param name="last">end subscript</param>
private static void Merge(int[] numbers, int first, int mid, int last)
{
    
int[] temp = new int[last - first + 1];
    
int index = 0;
    
int begin1 = first;
    
int end1 = mid;
    
int begin2 = mid + 1;
    
int end2 = last;

    
while ((begin1 <= end1) && (begin2 <= end2))
    {
        
if (numbers[begin1] > numbers[begin2])
            temp[index] 
= numbers[begin1++];
        
else
            temp[index] 
= numbers[begin2++];
        index
++;
    }
    
while (begin1 <= end1)
        temp[index
++= numbers[begin1++];
    
while (begin2 <= end2)
        temp[index
++= numbers[begin2++];
    
for (int i = 0, k = first; k <= last; k++, i++)
        numbers[k] 
= temp[i];
}

 

Go to my home page for more posts

posted on 2009-11-03 17:39  lantionzy  阅读(389)  评论(0编辑  收藏  举报