<< Chapter < Page Chapter >> Page >

6.2.4. merge sort

(From Wikipedia, the free encyclopedia)

In computer science , merge sort or mergesort is an O (n log n) comparison-based sorting algorithm . It is stable , meaning that it preserves the input order of equal elements in the sorted output. It is an example of the divide and conquer algorithmic paradigm. It was invented by John von Neumann in 1945 .

Merge sort

A merge sort algorithm used to sort an array of 7 integer values. These are the steps a human would take to emulate merge sort.

Algorithm

Conceptually, merge sort works as follows:

  1. Divide the unsorted list into two sublists of about half the size
  2. Divide each of the two sublists recursively until we have list sizes of length 1, in which case the list itself is returned
  3. Merge the two sublists back into one sorted list.

Mergesort 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 (see the merge function below for an example implementation).

Example: Using mergesort to sort a list of integers contained in an array :

Suppose we have an array A with indices ranging from A’first to A’Last. We apply mergesort to A(A’first..A’centre) and A(centre+1..A’Last) - where centre is the integer part of (A’first + A’Last)/2. When the two halves are returned they will have been sorted. They can now be merged together to form a sorted array.

In a simple pseudocode form, the algorithm could look something like this:

function mergesort(m)

var list left, right, result

if length(m) ≤ 1

return m

else

var middle = length(m) / 2

for each x in m up to middle

add x to left

for each x in m after middle

add x to right

left = mergesort(left)

right = mergesort(right)

result = merge(left, right)

return result

There are several variants for the merge() function, the simplest variant could look like this:

function merge(left,right)

var list result

while length(left)>0 and length(right)>0

if first(left) ≤ first(right)

append first(left) to result

left = rest(left)

else

append first(right) to result

right = rest(right)

if length(left)>0

append rest(left) to result

if length(right)>0

append rest(right) to result

return result

C++ implementation

Here is an implementation using the STL algorithm std::inplace_merge to create an iterative bottom-up in-place merge sort:

#include<iostream>

#include<vector>

#include<algorithm>

#include<iterator>

int main()

{

std::vector<unsigned>data;

for(unsigned i = 0; i<10; i++)

data.push_back(i);

std::random_shuffle(data.begin(), data.end());

std::cout<<"Initial: ";

std::copy(data.begin(),data.end(),std::ostream_iterator<unsigned>(std::cout," "));

std::cout<<std::endl;

for(unsigned m = 1; m<= data.size(); m *= 2)

{

for(unsigned i = 0; i<data.size() - m; i += m * 2)

{

std::inplace_merge(

data.begin() + i,

data.begin() + i + m,

data.begin() + std::min<unsigned>(i + m * 2, (unsigned)data.size()));

}

}

std::cout<<"Sorted: ";

std::copy(data.begin(),data.end(),std::ostream_iterator<unsigned>(std::cout," "));

Questions & Answers

how to study physic and understand
Ewa Reply
what is conservative force with examples
Moses
what is work
Fredrick Reply
the transfer of energy by a force that causes an object to be displaced; the product of the component of the force in the direction of the displacement and the magnitude of the displacement
AI-Robot
why is it from light to gravity
Esther Reply
difference between model and theory
Esther
Is the ship moving at a constant velocity?
Kamogelo Reply
The full note of modern physics
aluet Reply
introduction to applications of nuclear physics
aluet Reply
the explanation is not in full details
Moses Reply
I need more explanation or all about kinematics
Moses
yes
zephaniah
I need more explanation or all about nuclear physics
aluet
Show that the equal masses particles emarge from collision at right angle by making explicit used of fact that momentum is a vector quantity
Muhammad Reply
yh
Isaac
A wave is described by the function D(x,t)=(1.6cm) sin[(1.2cm^-1(x+6.8cm/st] what are:a.Amplitude b. wavelength c. wave number d. frequency e. period f. velocity of speed.
Majok Reply
what is frontier of physics
Somto Reply
A body is projected upward at an angle 45° 18minutes with the horizontal with an initial speed of 40km per second. In hoe many seconds will the body reach the ground then how far from the point of projection will it strike. At what angle will the horizontal will strike
Gufraan Reply
Suppose hydrogen and oxygen are diffusing through air. A small amount of each is released simultaneously. How much time passes before the hydrogen is 1.00 s ahead of the oxygen? Such differences in arrival times are used as an analytical tool in gas chromatography.
Ezekiel Reply
please explain
Samuel
what's the definition of physics
Mobolaji Reply
what is physics
Nangun Reply
the science concerned with describing the interactions of energy, matter, space, and time; it is especially interested in what fundamental mechanisms underlie every phenomenon
AI-Robot
what is isotopes
Nangun Reply
nuclei having the same Z and different N s
AI-Robot
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Data structures and algorithms. OpenStax CNX. Jul 29, 2009 Download for free at http://cnx.org/content/col10765/1.1
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Data structures and algorithms' conversation and receive update notifications?

Ask