Merge sort implementation (internal) and application scenario (external)

Source: Internet
Author: User

Merge sort can be ordered either internally or externally. Time complexity O (n*lgn) for merge sorting, O (N) for spatial complexity

In this case, you can sort by using an external merge:

If there are n file records in the external memory, can not be read into the memory at once, the file records in the external memory may be divided into a number of length l can be read into the memory of the segment, and then read into memory for internal sorting, ordered sub-file (merge segment) to re-write external memory. Then the merging segments are merged, so that the merging segments from small to large until orderly. However, when implementing 22 merging in the external sort, it is not possible to put two ordered and merged result segments in memory at the same time, so the main thing is to read and write external memory.

Main code for internal merge sort

void Mergeselction (Int*a, int*tmp, int begin1, int end1, int begin2, int end2)//merges two merge segments into an orderly merge segment
{
ASSERT (a);
int index = begin1;
while (begin1 <= end1&&begin2 <=end2)
{
if (a[begin1]<=a[begin2])
{
tmp[index++] = a[begin1++];
}
Else
{
tmp[index++] = a[begin2++];
}
}
while (Begin1 <=end1)
{
tmp[index++] = a[begin1++];
}
while (BEGIN2<=END2)
{
tmp[index++] = a[begin2++];
}
}

////////////

void _mergesort (int*a, int *tmp,int left, int. right)
{
ASSERT (a);
if (left < right)
{
int mid = left + (right-left)/2;
_mergesort (A, TMP, left, mid);
_mergesort (A, TMP, MID + 1, right);
Mergeselction (A, TMP, left, Mid, Mid + 1, right);
memcpy (A + left, tmp + left, (Right-left + 1) *sizeof (int));
}
}

//////////////
void mergesort (int *a, size_t size)
{
int *tmp = new Int[size];
_mergesort (A, TMP, 0, size-1);
Delete[] tmp;
}

Merge sort implementation (internal) and application scenario (external)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.