<< 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

what is mutation
Janga Reply
what is a cell
Sifune Reply
how is urine form
Sifune
what is antagonism?
mahase Reply
classification of plants, gymnosperm features.
Linsy Reply
what is the features of gymnosperm
Linsy
how many types of solid did we have
Samuel Reply
what is an ionic bond
Samuel
What is Atoms
Daprince Reply
what is fallopian tube
Merolyn
what is bladder
Merolyn
what's bulbourethral gland
Eduek Reply
urine is formed in the nephron of the renal medulla in the kidney. It starts from filtration, then selective reabsorption and finally secretion
onuoha Reply
State the evolution relation and relevance between endoplasmic reticulum and cytoskeleton as it relates to cell.
Jeremiah
what is heart
Konadu Reply
how is urine formed in human
Konadu
how is urine formed in human
Rahma
what is the diference between a cavity and a canal
Pelagie Reply
what is the causative agent of malaria
Diamond
malaria is caused by an insect called mosquito.
Naomi
Malaria is cause by female anopheles mosquito
Isaac
Malaria is caused by plasmodium Female anopheles mosquitoe is d carrier
Olalekan
a canal is more needed in a root but a cavity is a bad effect
Commander
what are pathogens
Don Reply
In biology, a pathogen (Greek: πάθος pathos "suffering", "passion" and -γενής -genēs "producer of") in the oldest and broadest sense, is anything that can produce disease. A pathogen may also be referred to as an infectious agent, or simply a germ. The term pathogen came into use in the 1880s.[1][2
Zainab
A virus
Commander
Definition of respiration
Muhsin Reply
respiration is the process in which we breath in oxygen and breath out carbon dioxide
Achor
how are lungs work
Commander
where does digestion begins
Achiri Reply
in the mouth
EZEKIEL
what are the functions of follicle stimulating harmones?
Rashima Reply
stimulates the follicle to release the mature ovum into the oviduct
Davonte
what are the functions of Endocrine and pituitary gland
Chinaza
endocrine secrete hormone and regulate body process
Achor
while pituitary gland is an example of endocrine system and it's found in the Brain
Achor
what's biology?
Egbodo Reply
Biology is the study of living organisms, divided into many specialized field that cover their morphology, physiology,anatomy, behaviour,origin and distribution.
Lisah
biology is the study of life.
Alfreda
Biology is the study of how living organisms live and survive in a specific environment
Sifune
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