在C 中合并排序算法

merge sort algorithm in C++

本文关键字:排序 算法 合并      更新时间:2023-10-16

我正在尝试编写一个C 程序,该程序使用合并算法对用户输入数组进行分类。

这是拆分函数:

void split(int numbers[], int size) {
    if (size == 1)
        return;
    int mid = size / 2;
    int firstPartSize = mid;
    int secondPartSize = size - mid;
    int *firstArray;
    firstArray = new int[firstPartSize];
    int *secondArray;
    secondArray = new int[secondPartSize];
    for (int i = 0; i < size; i++) {
        if (i < mid)
            firstArray[i] = numbers[i];
        else
            secondArray[i - mid] = numbers[i];
    }
    split(firstArray, firstPartSize);
    split(secondArray, secondPartSize);
    merge(numbers, firstArray, firstPartSize, secondArray, secondPartSize);
}

这是合并功能:

void merge(int outputArray[], int firstArray[], int n1, int secondArray[], int n2) {
    int k = 0;
    int i = 0;
    int j = 0;
    while (i < n1 && j < n2) {
        if (firstArray[i] < secondArray[j])
            outputArray[k++] = firstArray[i++];
        else
            outputArray[k++] = secondArray[j++];
    }
    while (i < n1)
        outputArray[k++] = firstArray[i++];
    while (j < n2)
        outputArray[k++] = secondArray[j++];
    for (int c = 0; c < n1+n2; c++)
    {
        cout << outputArray[c] << " ";
    }
}

当我尝试插入数组时,这就是我得到的

Enter the size of the array you want to sort:
3
Enter the elements of the array:
4
7
1
1 7 1 4 7 Press any key to continue

我在这里缺少什么?

代码总体上是正确的,并且一个简单的错误。您正在以递归步骤之一打印输出,因此将中间结果与答案混合在一起。

merge功能中删除cout并将其移出到main功能将有能力:

void merge(int outputArray[], int firstArray[], int n1, int secondArray[], int n2) {
    int k = 0;
    int i = 0;
    int j = 0;
    while (i < n1 && j < n2) {
        if (firstArray[i] < secondArray[j])
            outputArray[k++] = firstArray[i++];
        else
            outputArray[k++] = secondArray[j++];
    }   
    while (i < n1) 
        outputArray[k++] = firstArray[i++];
    while (j < n2) 
        outputArray[k++] = secondArray[j++];
}
int main(int argc, char *argv[]) {
    int a[] = {1, 4, 7}; 
    int n = sizeof(a) / sizeof(int);
    split(a, n); 
    cout << "The array is:n";
    for (int i = 0; i < n; i++) {
        cout << a[i] << " ";
    }   
    cout << endl;
    return 0;
}

输出:

The array is:
1 4 7