#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct nodenumber_s{
int *a;//存放数组int len;//当前数组元素个数
int cur;//当前数组中下次可用于归并的元素下标
};
struct nodetable_s{//该结构表示若干个非定长的数组
struct nodenumber_s *table;
int size;//数组个数
};
struct heapnode{
int value;
int list;//当前节点数据存在数组编号
int index;//当前节点数据在所在数组内部下标
};
/*下面两个函数用户堆排序*/
void heapdown(struct heapnode a[],int len,int start)
{
if (start < len)
{
int left = 2*start + 1;
int right = 2*start +2;
int maxindex = start;
if (left < len && a[left].value > a[start].value)
{
maxindex = left;
}
if (right < len && a[right].value > a[maxindex].value)
{
maxindex = right;
}
if (maxindex != start)
{
struct heapnode temp;
memcpy(&temp,&a[start],sizeof(struct heapnode));
memcpy(&a[start],&a[maxindex],sizeof(struct heapnode));
memcpy(&a[maxindex],&temp,sizeof(struct heapnode));
heapdown(a,len,maxindex);
}
}
}
void heapinit(struct heapnode a[],int len)
{
int start = len/2 -1;
while(start>=0)
{
int left = 2*start +1;
int right = 2*start +2;
int maxindex = start;
if (left < len && a[left].value > a[start].value)
{
maxindex = left;
}
if (right < len && a[right].value > a[maxindex].value)
{
maxindex = right;
}
if (maxindex != start)
{
struct heapnode temp;
memcpy(&temp,&a[start],sizeof(struct heapnode));
memcpy(&a[start],&a[maxindex],sizeof(struct heapnode));
memcpy(&a[maxindex],&temp,sizeof(struct heapnode));
heapdown(a,len,maxindex);
}
start--;
}
}
/*N个非定长升序数组 合并成一个升序数组*/
int multihebing(struct nodetable_s* table,int *a,int* plen)
{
if (table == NULL)
return -1;
int len = *plen;
int size = table->size;
struct nodenumber_s *nodenumber = table->table;
if (size == 0)
{
*plen = 0;
return 0;
}
struct heapnode *temp = (struct heapnode*)malloc(sizeof(struct heapnode)*size);
if (temp == NULL)
return -1;
for(int i = 0; i < size; i++)
{
temp[i].value = nodenumber[i].a[0];
temp[i].list = i;
nodenumber[i].cur = 1;
}
heapinit(temp,size);
int k = 0;
while(1)
{
if (k >= len)
{
*plen = len;
return 0;
}
a[k++] = temp[0].value;
int list = temp[0].list;
int outflag = 0;
int cur = nodenumber[list].cur;
int len = nodenumber[list].len;
if (cur < len)
{
temp[0].value = nodenumber[list].a[cur++];
nodenumber[list].cur++;
}
else
{
int flag = 0;
while(1)
{
list = (list+1)%size;
int cur = nodenumber[list].cur;
int len = nodenumber[list].len;
if (cur < len)
{
temp[0].value = nodenumber[list].a[cur++];
nodenumber[list].cur++;
temp[0].list = list;
break;
}
else
{
flag++;
if (flag > size)
{
outflag = 1;
break;
}
}
}
}
if (outflag == 1)
{
for(int i = size-1;i>0;i--)
{
memcpy(&temp[0],&temp[i],sizeof(struct heapnode));
heapdown(temp,i,0);
a[k++] = temp[0].value;
}
break;
}
heapdown(temp,size,0);
}
*plen = k;
return 0;
}