[Cpp] view plaincopyprint?
// Merge and sort
// The Merge Sorting Algorithm is an O (nlogn) algorithm. It is the worst, average, and the best time is O (nlogn ).
// But it requires additional storage space, which is limited on some machines with insufficient memory.
# Include <iostream>
# Include <stdio. h>
Using namespace std;
Int a [10] = {23,443,534, 12,312, 23 };
Void merge (int fir, int end, int mid)
{// Merge
Int tempArr [100];
Int fir1 = fir, fir2 = mid + 1;
For (int I = fir; I <= end; I ++)
{
If (fir1> mid) // After scanning the first half, assign the value to the last half.
TempArr [I] = a [fir2 ++];
Else if (fir2> end) // the second half of the scan is completed, and the first half is assigned a value.
TempArr [I] = a [fir1 ++];
// If the two ends are not scanned, select a smaller value to insert it behind the temporary array.
Else if (a [fir1]> a [fir2])
TempArr [I] = a [fir2 ++];
Else
TempArr [I] = a [fir1 ++];
}
// Copy the temporary data of the order number to the original array and return
For (int I = fir; I <= end; I ++)
{
A [I] = tempArr [I];
}
}
Void mergeSort (int fir, int end)
{
If (fir = end) return; // when there is only one element
Int mid = (fir + end)/2;
MergeSort (fir, mid); // recursively sorts the left half
MergeSort (mid + 1, end); // recursively sorts the right half
Merge (fir, end, mid); // merge
}
Int main ()
{
MergeSort (0, 9 );
For (int I = 0; I <= 9; I ++)
{
Printf ("% d \ t", a [I]);
}
// Cout <"Hello world! "<Endl;
Return 0;
}
// Merge and sort
// The Merge Sorting Algorithm is an O (nlogn) algorithm. It is the worst, average, and the best time is O (nlogn ).
// But it requires additional storage space, which is limited on some machines with insufficient memory.
# Include <iostream>
# Include <stdio. h>
Using namespace std;
Int a [10] = {23,443,534, 12,312, 23 };
Void merge (int fir, int end, int mid)
{// Merge
Int tempArr [100];
Int fir1 = fir, fir2 = mid + 1;
For (int I = fir; I <= end; I ++)
{
If (fir1> mid) // After scanning the first half, assign the value to the last half.
TempArr [I] = a [fir2 ++];
Else if (fir2> end) // the second half of the scan is completed, and the first half is assigned a value.
TempArr [I] = a [fir1 ++];
// If the two ends are not scanned, select a smaller value to insert it behind the temporary array.
Else if (a [fir1]> a [fir2])
TempArr [I] = a [fir2 ++];
Else
TempArr [I] = a [fir1 ++];
}
// Copy the temporary data of the order number to the original array and return
For (int I = fir; I <= end; I ++)
{
A [I] = tempArr [I];
}
}
Void mergeSort (int fir, int end)
{
If (fir = end) return; // when there is only one element
Int mid = (fir + end)/2;
MergeSort (fir, mid); // recursively sorts the left half
MergeSort (mid + 1, end); // recursively sorts the right half
Merge (fir, end, mid); // merge
}
Int main ()
{
MergeSort (0, 9 );
For (int I = 0; I <= 9; I ++)
{
Printf ("% d \ t", a [I]);
}
// Cout <"Hello world! "<Endl;
Return 0;
}