Cover Data Structures and Algorithms with Object-Oriented Design Patterns in Java
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_inline57766, the other of length tex2html_wrap_inline67461. 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:

displaymath67387

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_inline57766, the other of length tex2html_wrap_inline67461, into a single sorted sequence of length n. This can easily be done in O(n) time. (See Program gif).

   program32520
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

  equation32529

Equation gif is easily solved using repeated substitution:

eqnarray32535

Setting tex2html_wrap_inline67417 gives tex2html_wrap_inline67479.


next up previous contents index

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