SPOJ3370(Mergesort)
3370. MergesortProblem code: MERGSORT |
Simple. Sort the numbers on the standard input using the merge sort algorithm. Don't try to cheat by just calling your build in functions... I can see your source.
Input
On the standard input you will receive N (1 <= N <= 100000). Each number will fit in 32-bit integer
Output
Output the same integers in a sorted manner. Smallest to largest.
Example
Input: 7 3 2 5 4 3 Output: 2 3 3 4 5 7
//2009-05-17 12:55:06 Mergesort accepted 0.08 4.4M C++
#include <iostream>
#include <cstdio>
using namespace std;
const int N = 100004;
typedef struct
{
int key[N];
int length;
}SqList;
void Merge(SqList &L, int low, int mid, int high)
{//int p,int q,int r
int n1, n2;
int i, j, k;
//=========以下开辟二个辅助数组=========
n1 = mid - low + 1;
n2 = high - mid;
int *Left = new int[n1 + 1], *Right= new int[n2 + 1];
for(i = 0; i < n1; i++)
Left[i] = L.key[low + i];
for(i = 0;i < n2; i++)
Right[i] = L.key[mid + i + 1];
for(i = j = 0, k = low; k <= high; k++)
if(i == n1)
{
while(k <= high)
L.key[k++] = Right[j++];
break;
}
else if(j == n2)
{
while(k <= high)
L.key[k++] = Left[i++];
break;
}
else if(Left[i] <= Right[j])
L.key[k] = Left[i++];
else
L.key[k] = Right[j++];
}
void MergeSort(SqList &L, int l, int h)
{
int low = l, high = h, mid;
if(low < high)
{
mid = (low + high) / 2;
MergeSort(L,low,mid);// the left
MergeSort(L,mid + 1, high);// the right
Merge(L, low, mid, high);
}
}
int main()
{
SqList L;
L.length = 0;
while(scanf("%d", &L.key[++L.length]) != EOF)
;
L.length--;
MergeSort(L, 1, L.length);
for(int i = 1; i <= L.length; i++)
if(i != L.length)
printf("%d ", L.key[i]);
else
printf("%d\n", L.key[i]);
return 0;
}
#include <iostream>
#include <cstdio>
using namespace std;
const int N = 100004;
typedef struct
{
int key[N];
int length;
}SqList;
void Merge(SqList &L, int low, int mid, int high)
{//int p,int q,int r
int n1, n2;
int i, j, k;
//=========以下开辟二个辅助数组=========
n1 = mid - low + 1;
n2 = high - mid;
int *Left = new int[n1 + 1], *Right= new int[n2 + 1];
for(i = 0; i < n1; i++)
Left[i] = L.key[low + i];
for(i = 0;i < n2; i++)
Right[i] = L.key[mid + i + 1];
for(i = j = 0, k = low; k <= high; k++)
if(i == n1)
{
while(k <= high)
L.key[k++] = Right[j++];
break;
}
else if(j == n2)
{
while(k <= high)
L.key[k++] = Left[i++];
break;
}
else if(Left[i] <= Right[j])
L.key[k] = Left[i++];
else
L.key[k] = Right[j++];
}
void MergeSort(SqList &L, int l, int h)
{
int low = l, high = h, mid;
if(low < high)
{
mid = (low + high) / 2;
MergeSort(L,low,mid);// the left
MergeSort(L,mid + 1, high);// the right
Merge(L, low, mid, high);
}
}
int main()
{
SqList L;
L.length = 0;
while(scanf("%d", &L.key[++L.length]) != EOF)
;
L.length--;
MergeSort(L, 1, L.length);
for(int i = 1; i <= L.length; i++)
if(i != L.length)
printf("%d ", L.key[i]);
else
printf("%d\n", L.key[i]);
return 0;
}