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)