【问题标题】:my merge sort is not giving proper sorted array, can anyone explain?我的合并排序没有给出正确的排序数组,谁能解释一下?
【发布时间】:2017-07-13 17:43:30
【问题描述】:

我花了几个小时来理解和实现这个算法,我很确定,我正在按照标准算法做所有事情,但它仍然不起作用。 我正在关注一本名为“Thomas H cormen 的算法简介”的书

#include<iostream>
using namespace std;

//function to divide the array until it has only one element
void merge_sort(int[], int, int);

// function to merge two sorted arrays
void merge(int[], int, int, int);

// global array - to write the final sorted array in this
int na[100];

void main() {
    int a[50]; //input array
    cout << "Enter an unsorted array of 10 elements" << endl;
    for (int i = 0; i < 10; i++) {
        cin >> a[i];
    }
    merge_sort(a, 0, 9);  // calling merge_sort
    for (int i = 0; i < 10; i++) {
        //print final array
        cout << na[i] << endl;
    }
}

void merge_sort(int a[], int p, int r) {
    // p is 0 , r is final bound
    if (p < r) {
        int q;
        q = (p + r) / 2; //finding middle element
        merge_sort(a, p, q);
        merge_sort(a, q + 1, r);
        merge(a, p, q, r);
     }

}

// for two sorted sub-array from p to q and from q+1 to r, this function 
// will compare first element of each sub-array and will place the smaller 
// one in final array until every element is sub-array is in final sorted 
//array
void merge(int a[], int p, int q, int r) {
    int n1 = q - p + 1;
    int n2 = r - q;
    int l[50];
    int ri[50];
    for (int i = 0; i < n1; i++) {
        l[i] = a[p + i ];
    }
    l[n1] = 99999;

    for (int j = 0; j < n1; j++) {
        ri[j] = a[q + j + 1];
    }
    ri[n2] = 99999;

    int i = 0;
    int j = 0;
    for (int k = p; k <= r; k++) {
         if (l[i] <= ri[j]) {
            na[k] = l[i];
            i = i + 1;
        }
        else {
            na[k] = ri[j];
            j = j + 1;
        }
     }

}

【问题讨论】:

  • 你应该更新你的资源,void main()是不可接受的。
  • 您可以使用调试器逐行检查代码和变量行为。
  • 1) j &lt; n1; --> j &lt; n2;
  • 2) 不要使用int na[100];。所以cout &lt;&lt; na[i] --> cout &lt;&lt; a[i], na[k] = l[i]; --> a[k] = l[i]; 因为你使用int a[] 作为排序数组。
  • 哦.. 2 点有效@bluepixy ,但是如何将结果写入有效而不是?如果你不介意

标签: c++ algorithm sorting merge


【解决方案1】:

您正在使用a 中的值进行合并,但您将已排序的子数组放入na。如果子数组已排序,merge 操作只会为您提供已排序的数组。正如 BLUEPIXY 所建议的那样,您需要使用一个容器来存储已排序的子数组和合并已排序的子数组:无论您为此目的使用 a 还是 na 都无关紧要,但 a 将是更好的选择,因为您已经拥有它.

【讨论】:

    【解决方案2】:
    1. 尝试阅读在 StackOverflow 上提问的指南。

    2. 1234563 /li>

    否则在每个对merge_sort(:)的函数调用中合并na[]的段并将其复制到a[]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多