Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何实现合并排序自";算法简介;科尔曼公司_C_Algorithm_Mergesort - Fatal编程技术网

C 如何实现合并排序自";算法简介;科尔曼公司

C 如何实现合并排序自";算法简介;科尔曼公司,c,algorithm,mergesort,C,Algorithm,Mergesort,我正在学习Cormen和Co.的算法,我在从伪代码实现合并排序时遇到了问题。我是通过以下方式编写的: $ gcc -Wall -g merge_sort.c 我有一个问题,因为对于数字: 2 4 5 7 1 2 3 6 结果是: 1 2 2 3 3 4 5 5 我试图仔细阅读伪代码,但这对我没有帮助。 我想知道我做错了什么。下面是我的代码: #include <stdio.h> #define SIZE 8 void merge(int *array_of_integer

我正在学习Cormen和Co.的算法,我在从伪代码实现合并排序时遇到了问题。我是通过以下方式编写的:

$ gcc -Wall -g merge_sort.c
我有一个问题,因为对于数字:

2 4 5 7 1 2 3 6
结果是:

1 2 2 3 3 4 5 5 
我试图仔细阅读伪代码,但这对我没有帮助。 我想知道我做错了什么。下面是我的代码:

#include <stdio.h>

#define SIZE 8

void merge(int *array_of_integers, int p, int q, int r) {
    int n1 = q - p + 1;
    int n2 = r - q; 
    int i, j, k;
    int left_array[n1 + 1];
    int right_array[n2 + 1];

    for (i = 0; i < n1; i++)
        left_array[i] = array_of_integers[p + i];
    for (j = 0; j < n2; j++)
        right_array[j] = array_of_integers[q + j];

    i = 0;
    j = 0;

    for (k = p; k < r; k++){
        if (left_array[i] <= right_array[j]) {
            array_of_integers[k] = left_array[i];
            i++;
        } else {
            array_of_integers[k] = right_array[j];
            j++;
        }   
    }
}

void merge_sort(int *array_of_integers, int p, int r) {
    if (p < r) {
        int q = (p + r) / 2;
        merge_sort(array_of_integers, p, q);
        merge_sort(array_of_integers, q + 1, r);
        merge(array_of_integers, p, q, r);
    }
}

void print_array(int *array_of_integers, int amout_of_integers) {
    int i;
    for(i = 0; i < amout_of_integers; i++)
        printf("%d ", array_of_integers[i]);
    puts("");
}

int main(void) {
    int dataset[] = { 2, 4, 5, 7, 1, 2, 3, 6 };

    print_array(dataset, SIZE);
    merge_sort(dataset, 0, SIZE);
    print_array(dataset, SIZE);

    return 0;
}
#包括
#定义大小8
无效合并(整数的整数数组,整数p,整数q,整数r){
int n1=q-p+1;
int n2=r-q;
int i,j,k;
int左_数组[n1+1];
int右_数组[n2+1];
对于(i=0;iif(left_array[i]代码中有两个问题

首先,您需要澄清传递的参数的含义。在merge_sort中,p是第一个要排序的元素,r是最后一个要排序的元素。但是,在调用merge_sort的地方,主要是传递0和SIZE。这里,0是第一个要排序的元素,但是SIZE不能是最后一个元素,因为它是(大概)要排序的元素数。在您的示例中,您传递的是8,但最后一个要排序的元素是7。因此,请决定是要更改merge_sort,使r为元素数,还是要将main更改为pass SIZE-1。类似地,在merge中,p似乎是第一个要合并的元素,q是第一个ra的最后一个元素nge(因此q+1是第二个范围的第一个),r是第二个范围的最后一个元素。但是当你从\u整数数组复制到右\u数组时,你从q+j复制。当j为零时,这复制第一个范围的最后一个元素,但你想要第二个范围的第一个元素。所以你需要清除索引的这些用法。(另外,左_数组和右_数组只需要n1和n2元素,而不是n1+1和n2+1。)还要检查k上的循环,
中的(k=p;k
。该循环的延续条件应该是什么


第二,当您合并左_数组和右_数组时,您没有考虑数组可能为空的事实(因为以前所有元素都是从中复制出来的),因此比较左_数组[i]和右_数组[j]不起作用,因为i或j分别表示左_数组或右_数组之外的元素。例如,如果i已达到其极限(n1),那么您不应该进行比较。相反,您应该只从右数组中获取一个元素。

这一个虽然用Java实现,但逻辑显然是相同的。我已经考虑了Eric在回答中建议的所有要点。请查看代码,它是自解释的

import java.util.*;
class MergeSort
{

    public static void main(String args[])
    {
        int testArray[] = {1,3,5,3,1,7,8,9};
        mergeSort(testArray,0,testArray.length-1);
        System.out.println(Arrays.toString(testArray));
    }

    protected static void mergeSort(int arr[], int p, int r)
    {
        int q;
        if (p<r)
        {
            q = (p+r)/2;
            mergeSort(arr,p,q);
            mergeSort(arr, q+1, r);
            merge(arr,p,q,r);   
        }   
    }

    protected static void merge(int arr[], int p, int q, int r)
    {    
        int n = q-p+1;
        int m = r-q;

        int L[] = new int[n+1];
        int R[] = new int[m+1];
        int i,j,k;

        for(i=0; i< n; i++)
        {
            L[i] = arr[p+i];    
        }
        for(j=0; j< m; j++)
        {
            R[j] = arr[q+j+1];    
        }

        L[n] = Integer.MAX_VALUE;
        R[m] = Integer.MAX_VALUE;

        i = 0;
        j = 0;
        for(k = p; k<= r; k++)
        {

            if( L[i]<=R[j])
            {
                arr[k] = L[i];
                i = i+1;
            }
            else
            {
                arr[k] = R[j];
                j = j+1;

            }           
        }
    }
}
import java.util.*;
类合并排序
{
公共静态void main(字符串参数[])
{
int testArray[]={1,3,5,3,1,7,8,9};
合并排序(testArray,0,testArray.length-1);
System.out.println(Arrays.toString(testArray));
}
受保护的静态无效合并排序(int arr[],int p,int r)
{
int-q;
如果(p
这个对我有用
//MergeSortRevisionAgain.cpp:定义控制台应用程序的入口点。
//理解合并排序
#包括
使用std::cout;
使用std::endl;
//合并排序函数的声明
无效合并(inta[],intp,intq,intr);
int*mergeSort(inta[],intp,intr);
int main()
{
/*我要测试合并排序的代码*/
int myArray[]{2,3,5,7,1,4,7,9};
int lengthOfArray=sizeof(myArray)/sizeof(myArray[1]);
int*sortedOutput=mergeSort(myArray,0,lengthOfArray-1);
对于(inti=0;i,这里是我的尝试。
已知错误:由于INT_MAX用作哨兵,对包含INT_MAX的数组进行排序可能会导致合并期间指针溢出

#include <stdio.h>
#include <limits.h>
void merge(int A[], unsigned int p, unsigned int q, unsigned int r){
    unsigned int n1 = q - p; //differs from book because C indexes from 0
    unsigned int n2 = r - q;


    int L[n1 + 1]; // L contains the first elem of A, up to the midpoint (not including the midpoint)
    int R[n2 + 1]; // R contains the elems including the midpoint of A all the way to the end.

    L[n1] = INT_MAX; //INT_MAX is our sentinel, which will be used in the merge step. No possible int will be greater than INT_MAX, so during the merge,
    R[n2] = INT_MAX; // INT_MAX is similar to the infinity used in the book

    for (unsigned int i = 0; i < n1; i++){
        L[i] = A[p + i];
    }

    for (unsigned int i = 0; i < n2; i++){
        R[i] = A[q + i];
    }
    // Now we just need to merge L and R and sort A
    // The sorting occurs here, during the merge.
    unsigned int i = 0;
    unsigned int j = 0;

    for (unsigned int k = p; k < r; k++){
        if (L[i] <= R[j]){
            A[k] = L[i];
            i++;
        }
        else{
            A[k] = R[j];
            j++;
        }
    }
}
void merge_sort(int A[], unsigned int p, unsigned int r) { // input is array A, first elem p, and last elem + 1 r

    if (p < r - 1) { //differs from book... since C indexes from 0, if we have an array of size 1, we will subtract 1 to get 0 and then hit the base case

        // Otherwise, find the midpoint and divide and conquer
        unsigned int q = (p + r) / 2; //q is the midpoint of A
        merge_sort(A, p, q); //this must process the midpoint
        merge_sort(A, q, r); //this must process the elem after the midpoint to the last elem
        merge(A, p, q, r);
        return;


    }

}


int main(){

    int A[] = {432, 5, 99, 101, 43};
    unsigned int len_A = sizeof(A)/sizeof(A[0]);

    printf("original order of elems in A: \n");

    for (unsigned int i = 0; i < len_A; i++){
        printf("%d ", A[i]);
    }

    merge_sort(A, 0, len_A);

    printf("\n\n");
    printf("after performing merge_sort: \n");


    for (unsigned int i = 0; i < len_A; i++){
        printf("%d ", A[i]);
    }

    printf("\n\n");

return 0;
}
#包括
#包括
无效合并(整数A[],无符号整数p,无符号整数q,无符号整数r){
unsigned int n1=q-p;//与book不同,因为C索引来自0
无符号整数n2=r-q;
int L[n1+1];//L包含A的第一个元素,直到中点(不包括中点)
int R[n2+1];//R包含从A的中点一直到终点的元素。
L[n1]=INT_MAX;//INT_MAX是我们的哨兵,将在合并步骤中使用。任何可能的INT都不会大于INT_MAX,因此在合并过程中,
R[n2]=INT_MAX;//INT_MAX类似于书中使用的无穷大
for(无符号整数i=0;iif(L[i]这里可能有一个代码复查堆栈交换站点:。我自己不使用它,但我不确定这是否是关于主题的更多内容…此算法已被破坏:使用sentinel值来避免根据数组长度测试索引值是一种注定要失败的方法。如果数组包含大于等于>123456798?<代码>?你可能不应该考虑这本参考书。谢谢埃里克!在你的帮助下,我解决了这个问题。再次感谢。我把正确的代码推到GITHUB。我认为你的新代码不能正确处理合并LeftTyLoad和RealItLoad时发生的所有情况。在Cormen的书中,他们用无穷胡来比较整数,所以我用了一个大整数,所以我想现在应该是更好的解决方案。当然,它不是一个漂亮的解决方案,但我只想解决一个简单的练习。@ GITHUUB链接断开了。任何问题。编辑您的代码和对代码的注释,
This one worked for me

    // MergeSortRevisionAgain.cpp : Defines the entry point for the console application.
//Understanding merge sort
#include <iostream>

using std::cout;
using std::endl;


//The declaration of the merge sort function
void merge(int A[], int p, int q, int r);
int* mergeSort(int A[], int p, int r);


int main()
{

    /*My Code to test for the merge sort*/
    int myArray[]{ 2,3,5,7,1,4,7,9};
    int lengthOfArray = sizeof(myArray) / sizeof(myArray[1]);
    int* sortedOutput = mergeSort(myArray, 0, lengthOfArray-1);

    for (int i = 0; i <lengthOfArray; i++)
    {
        cout << sortedOutput[i] << " ";
    }

    cout << endl;


    return 0;
}


void merge(int A[], int p, int q, int r)
{
    //Declaration of number of variable in each half
    int n1 = q - p + 1;                                                             //1. n1 = q - p + 1
    int n2 = r - q;                                                                 //2. n2 = r-q

    //Declaration of left and right part of the array
    int* leftArray= new int[n1+1] ;                                                 //3. Let L[1...n1+1] and ... 
    int* rightArray= new int[n2+1] ;                                                //... R[1...n2+1] be new arrays

    //Entering the for loop for the left side
    for (int i = 0; i < n1; i++)                                                    //4.for i = 1 to n1 NB(change i to 0 since index in c++ starts from 0)
    {
        leftArray[i] = A[p + i ];                                                   //5. L[i] = A[p+i-1] NB(change to A[p+i] since "i" was changed to 0 hence A[p,...,p+i)
    }

    //Entering the for loop for the right side
    for (int  j = 0; j < n2; j++)                                                   //6. for j = 1 to n2 NB(change j j= 0 since index in c++ starts from 0)
    {
        rightArray[j] = A[q + j+1];                                                 //7. R[i] = A[q + j ] NB(change to A[q+j+1] since "j" was changed to 0  hence A[q+1,...q+1+j]
    }

    leftArray[n1] = 999;                                                            //8. Set L[n1+1] = sentinel NB last value in leftArray will be the sentinel
    rightArray[n2] = 999;                                                           //9. Set L[n2 + 2] = sentinel NB last value in rightArray will be the sentinel

    int i = 0;                                                                      //10. i = 1 change to i = 0 since index starts from 0 in c++
    int j = 0;                                                                      //11. j = 1 change to j = 0 since index starts from 0 in c++

    for (int k = p; k <= r; k++)                                                    //12. for k = p to r - change as specified in code since index of array p = 0, r = lengthofArray - 1
    {
        if (leftArray[i] <= rightArray[j])                                          //13. L[i] <= R[j]
        {
            A[k] = leftArray[i];                                                    //14. A[k] = L[i]
            i = i + 1;                                                              //15. i = i + 1
        }
        else
        {
            A[k] = rightArray[j];                                                   //16. A[k] = R[j]
            j = j + 1;                                                              //17. j = j+1;
        }
    }

    delete leftArray;                                                               //18. Free allocated dynamic memory for leftArray
    leftArray = nullptr;                                                            //19. Set pointer to nullptr to prevent access to deleted memory
    delete rightArray;                                                              //20. Free allocated dynamic memory for rightArray              
    rightArray = nullptr;                                                           //21. Set pointer to nullptr to prevent access to deleted memory
}

int* mergeSort(int A[], int p, int r)
{
    if (p < r)
    {
        int q = floor((p + r) / 2);
        mergeSort(A, p, q );
        mergeSort(A, q + 1, r);
        merge(A, p, q, r);
    }

    return A;
}
#include <stdio.h>
#include <limits.h>
void merge(int A[], unsigned int p, unsigned int q, unsigned int r){
    unsigned int n1 = q - p; //differs from book because C indexes from 0
    unsigned int n2 = r - q;


    int L[n1 + 1]; // L contains the first elem of A, up to the midpoint (not including the midpoint)
    int R[n2 + 1]; // R contains the elems including the midpoint of A all the way to the end.

    L[n1] = INT_MAX; //INT_MAX is our sentinel, which will be used in the merge step. No possible int will be greater than INT_MAX, so during the merge,
    R[n2] = INT_MAX; // INT_MAX is similar to the infinity used in the book

    for (unsigned int i = 0; i < n1; i++){
        L[i] = A[p + i];
    }

    for (unsigned int i = 0; i < n2; i++){
        R[i] = A[q + i];
    }
    // Now we just need to merge L and R and sort A
    // The sorting occurs here, during the merge.
    unsigned int i = 0;
    unsigned int j = 0;

    for (unsigned int k = p; k < r; k++){
        if (L[i] <= R[j]){
            A[k] = L[i];
            i++;
        }
        else{
            A[k] = R[j];
            j++;
        }
    }
}
void merge_sort(int A[], unsigned int p, unsigned int r) { // input is array A, first elem p, and last elem + 1 r

    if (p < r - 1) { //differs from book... since C indexes from 0, if we have an array of size 1, we will subtract 1 to get 0 and then hit the base case

        // Otherwise, find the midpoint and divide and conquer
        unsigned int q = (p + r) / 2; //q is the midpoint of A
        merge_sort(A, p, q); //this must process the midpoint
        merge_sort(A, q, r); //this must process the elem after the midpoint to the last elem
        merge(A, p, q, r);
        return;


    }

}


int main(){

    int A[] = {432, 5, 99, 101, 43};
    unsigned int len_A = sizeof(A)/sizeof(A[0]);

    printf("original order of elems in A: \n");

    for (unsigned int i = 0; i < len_A; i++){
        printf("%d ", A[i]);
    }

    merge_sort(A, 0, len_A);

    printf("\n\n");
    printf("after performing merge_sort: \n");


    for (unsigned int i = 0; i < len_A; i++){
        printf("%d ", A[i]);
    }

    printf("\n\n");

return 0;
}