Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

Example-Merge Sorting

 

Sorting algorithms and sorters are covered in detail in Chapter gif. In this section we consider a divide-and-conquer sorting algorithm--merge sort . Given an array of n items in arbitrary order, the objective is to rearrange the elements of the array so that they are ordered from the smallest element to the largest one.

The merge sort algorithm sorts a sequence of length n>1 by splitting it into to subsequences--one of length tex2html_wrap_inline58047, the other of length tex2html_wrap_inline67744. Each subsequence is sorted and then the two sorted sequences are merged into one.

Program gif defines the method MergeSort which takes three arguments, array, i, and n. The method sorts the following n elements:

displaymath67670

The MergeSort method calls itself as well as the Merge method. The purpose of the Merge method is to merge two sorted sequences, one of length tex2html_wrap_inline58047, the other of length tex2html_wrap_inline67744, into a single sorted sequence of length n. This can easily be done in O(n) time. (See Program gif).

   program32768
Program: Divide-and-conquer example--merge sorting.

The running time of the MergeSort method depends on the number of items to be sorted, n. Although Program gif works correctly for arbitrary values of n, it is much easier to determine the running time if we assume that n is a power of two. In this case, the running time is given by the recurrence

  equation32777

Equation gif is easily solved using repeated substitution:

eqnarray32783

Setting tex2html_wrap_inline67700 gives tex2html_wrap_inline67762.


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.