递归归并排序传递指向零的指针

C++ Recursive Merge Sort passing pointers resulting in zeros

本文关键字:指针 归并排序 递归      更新时间:2023-10-16

我在赋值时遇到了一些麻烦,我要转换一个使用向量的特定递归归并排序算法,但使用数组代替。

这是我到目前为止所做的,我相信Sort()工作得很好。但是,Merge()是我认为问题所在…谢谢你!

#include "genlib.h"
#include <iostream>
/* Private function prototypes */
void Sort(int arr[], int n);
void Merge(int *arr[], int *arr1[], int *arr2[], int n1, int n2);
/* Main program */
int main() {
    int arr[] = {88, 10, 20, 50, 7, 44, 99, 9, 900, 44};
    int n = sizeof(arr) / sizeof(arr[0]);   
    Sort(arr, n);
    cout << "[";
    for (int i = 0; i < n; i++) {           // prints out sorted array
        if (i > 0) cout << ", ";
        cout << arr[i];
    }
    cout << "]" << endl;
    return 0;
}

/*
* Function: Sort
* Usage: void MergeSort(int arr[], const int START, const int END);
* ----------------------------------------------------------------------------------
* This function sorts the elements of the array into increasing numerical order 
* using the merge sort algorithm, which consists of the following steps:
*   1. Divide the array into two halves.
*   2. Sort each of these smaller array recursively.
*   3. Merge the two arrays back into the original one.
*
* NOTE: Although in the book, the creation of the 2 divided arrays would occur in 
*       this function, I had a lot of difficulty trying to get the recursive sort
*       to work with dynamic arrays. This is due to my inability to delete the 
*       array from memory before it gets called again.
*       I opted to dynamically create the array in Merge() instead.
*/
void Sort(int arr[], int n) {
    if (n <= 1) return; // base case
    int mid = n/2;
    int *arr1 = NULL; 
    int *arr2 = NULL; 
    arr1 = new int[mid];
    arr2 = new int[n-mid];
    for (int i=0; i<n; i++) {
        if (i < (mid)) {
            arr1[i] = arr[i];
        } else {
            arr2[i-(mid)] = arr[i];
        }
    }
    Sort(arr1,mid);
    delete[] arr1;
    Sort(arr2,n-mid);
    delete[] arr2;
    for (int i=0; i<n; i++) {
        arr[i] = 0;
    }
    Merge(&arr, &arr1, &arr2, n/2, n/2);
}
/*
* Function: Merge
* Usage: void Merge(int arr[], const int START, const int MID, const int END);
* ----------------------------------------------------------------------------------
* This function merges two sorted arrays into the original array, which should be 
* empty before this operation. Because the input arrays are sorted, the 
* implementation can always select the first unused element in one of the input 
* array vectors to fill the next position.
*/
void Merge(int *arr[], int *arr1[], int *arr2[], int n1, int n2) {
    int p1 = 0;
    int p2 = 0;
    while (p1 < n1 && p2 < n2) {
        if (arr1[p1] < arr2[p2]) {
            arr[p1+p2] = arr1[p1];
            p1++;
        } else {
            arr[p1+p2] = arr2[p2];
            p2++;
        }
    }
    while (p1 < n1) { 
        arr[p1+p2] = arr1[p1];
        p1++;
    }
    while (p2 < n2) { 
        arr[p1+p2] = arr2[p2];
        p2++;
    }
}

下面是vector的原始实现:

/*
 * Function: Sort
 * -------------- * This function sorts the elements of the vector into
 * increasing numerical order using the merge sort algorithm,
 * which consists of the following steps:
 *
 * 1. Divide the vector into two halves.
 * 2. Sort each of these smaller vectors recursively.
 * 3. Merge the two vectors back into the original one.
 */
void Sort(Vector<int> & vec) {
    int n = vec.size();
    if (n <= 1) return;
    Vector<int> v1;
    Vector<int> v2;
    for (int i = 0; i < n; i++) {
        if (i < n / 2) {
            v1.add(vec[i]);
        } else {
        v2.add(vec[i]);
        }
    }
    Sort(v1);
    Sort(v2);
    vec.clear();
    Merge(vec, v1, v2);
}
/*
 * Function: Merge
 * --------------- * This function merges two sorted vectors (v1 and v2) into the
 * vector vec, which should be empty before this operation.
 * Because the input vectors are sorted, the implementation can
 * always select the first unused element in one of the input
 * vectors to fill the next position.
 */
void Merge(Vector<int> & vec, Vector<int> & v1, Vector<int> & v2) {
    int n1 = v1.size();
    int n2 = v2.size();
    int p1 = 0;
    int p2 = 0;
    while (p1 < n1 && p2 < n2) {
        if (v1[p1] < v2[p2]) {
            vec.add(v1[p1++]);
        } else {
        vec.add(v2[p2++]);
        }
    }
    while (p1 < n1) vec.add(v1[p1++]);
    while (p2 < n2) vec.add(v2[p2++]);
}

问题在"Sort":

Sort(arr1,mid);
delete[] arr1;
Sort(arr2,n-mid);
delete[] arr2;
for (int i=0; i<n; i++) {
    arr[i] = 0;
}
Merge(&arr, &arr1, &arr2, n/2, n/2);

首先对数组进行排序,然后删除它(结果arr1是一个空指针)和arr2是一样的。

当您开始合并时,您已经删除了数据并释放了内存

一个解决方案是,将"delete"语句移到Merge-call下面:

Sort(arr1,mid);
Sort(arr2,n-mid);
for (int i=0; i<n; i++) {
    arr[i] = 0;
}
Merge(&arr, &arr1, &arr2, n/2, n/2);
delete[] arr1;
delete[] arr2;

这样你就不会丢失数据。因为你是用"new"语句创建数组的,所以你不应该把"delete"语句去掉。

希望这能解决你的问题

现在,到Merge的参数是指针数组,但它足以作为普通数组传递它们:

void Merge(int arr[], int arr1[], int arr2[], int n1, int n2)

也可以作为指针传递:

void Merge(int *arr, int *arr1, int *arr2, int n1, int n2)

从可读性的角度来看,我个人认为第一种选择可能更好。

在sort中,只传递没有&的数组:

Merge(arr, arr1, arr2, n/2, n/2);

此外,您还有另一个问题,这是非常严重的:您删除arr1arr2之前,将它们传递给Merge函数!这意味着Merge将访问未分配的内存,这非常糟糕。