将K列表与N个项目合并不适用于大K或N(K或N> 200)

时间:2019-11-02 15:50:43

标签: c++ algorithm merge

我实现了一种算法,用于将K个排序的列表与N个项目合并。该代码适用于较小的输入数据,但对于大于200的N,K,它将崩溃。我需要评估此算法,因此我需要长度超过1000的列表。

我测试了所有必要的功能,包括MinHeap的构造,一切正常。

struct Node {
    int data;
    struct Node* next;
};

struct List {
    int size;
    Node* head;
};

struct HeapObject {
    int listIndex;
    int key;
};
Node* addNode(List* list, int data){
    auto* node = new Node;
    node->data = data;
    node->next = nullptr;
    ++list->size;
    if(list->head == nullptr) list->head = node;
    else
    {
        node->next = list->head;
        list->head = node;
    }
    return node;
}

List* newList(){
    auto* list = new List;
    list->size = 0;
    list->head = nullptr;
    return list;
}

List* generateSortedList(int size){
    auto* arr = new int[size];
    List* list = newList();
    FillRandomArray(arr,size,100,50000,true,2);//generate arrays with random elements in descending order, i cant provide that function since its in another header.
    for(int i = 0; i < size; i++){
        addNode(list,arr[i]);
    }
    return list;
}

List* generateLists(int k, int n){
    auto* lists = new List[k];
    for(int i = 0; i < k; i++)
    {
        lists[i] = *generateSortedList(n);
    }
    return lists;
}
int parent(int i) {
    return (i-1)/ 2;
}

void topDownMinHeap(HeapObject* heap, int size) {
    for (int i = 1; i < size; i++) {
        int j = i;
        while (j > 0 && heap[j].key < heap[parent(j)].key) {
            swap(heap[j], heap[parent(j)]);
            j = parent(j);
        }
    }
}

void pop(List* list){
    Node* aux = list->head;
    list->head = list->head->next;
    delete aux;
    --list->size;
}
void merge(List* lists, int k, int n, int* output)
{
    auto* minHeap = new HeapObject[k];

    for(int i = 0; i < k; i++){
        minHeap[i].key = lists[i].head->data;
        minHeap[i].listIndex = i;
    }

    topDownMinHeap(minHeap,k);

    for(int i = 0; i < n * k; i++){
        output[i] = minHeap[0].key;
        pop(&lists[minHeap[0].listIndex]);
        if(lists[minHeap[0].listIndex].size != 0) minHeap[0].key = lists[minHeap[0].listIndex].head->data;
        else minHeap[0].key = INT32_MAX;
        topDownMinHeap(minHeap,k);
    }
}
int main() {
    int* output = new int[1000];
    List* lists = generateLists(100,50);
    merge(lists,100,50,output);
    return 0;
}

0 个答案:

没有答案