http://www.spoj.pl/problems/MERGSORT/
2009-05-17 12:55:06 Mergesort accepted 0.08 4.4M C++
此题出的太好的,巩固了一遍归并排序。不过有点点失误。
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 <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;
}