简体   繁体   中英

Counting Comparisons with Merge Sort

Right now I'm learning about algorithms, and I was encouraged to go back through all the different sorting methods to find out how many comparisons each kind takes to sort through an array of numbers. I need to implement a count inside this Merge Sort program which works, but I'm getting a little lost as far as where it needs to go. If anyone could point me in the right direction, I'd really appreciate it.

//MergeSort.h

#include <iostream>
using namespace std;
void merge_sort(int A[], int low, int high);
void merge(int A[], int low, int mid, int high);

void merge_sort(int A[], int low, int high)
{
   int mid;
   if(low<high)
   {
      mid=(low+high)/2;
      merge_sort(A,low,mid);
      merge_sort(A,mid+1,high);
      merge(A,low,mid,high);

   }
}

void merge(int A[], int low, int mid, int high)
{
    int h, i, j, B[100], k;
    h = low;
    i = low;
    j = mid + 1;

    while ((h <= mid) && (j <= high))
    {
        if (A[h] <= A[j])
        {
            B[i] = A[h];
            h++;
        }
        else
        {
            B[i] = A[j];
            j++;
        }
        i++;
    }

    if (h > mid)
    {
        for (k = j;k <= high;k++)
        {
            B[i] = A[k];
            i++;
        }
    }
    else
    {
        for (k = h;k <= mid;k++)
        {
            B[i] = A[k];
            i++;
        }
    }

    for (k = low;k <= high;k++)
    {
        A[k] = B[k];
    }
}

and

//MergeSort.cpp

#include <iostream>
using namespace std;

#include "MergeSort.h"
#include <ctime>

int main() 
{
    int A[1000], n = 100, i;
    srand(time(NULL));

    cout << "Here are " << n << " random numbers: \n";
    for (i = 0; i < n; i++)
    {
        A[i] = rand() % 100;
        cout << " " << A[i];
    }

    merge_sort(A, 0, n-1);

    cout << "\n\nThe sorted array is: ";
    for (int i=0;i<n;i++)
        cout << A[i] <<" ";

    cout<<endl<<endl;
    system("pause");
}

一种计算比较次数的简单方法是将mergemerge-sort功能从void更改为返回其中的比较次数并递归计数。

B的长度数组只有100。它将被绑定。

The simplest way to do this is to use a static global variable, and increment it with each compare of A[] in merge(), then have the main program display the count after a sort. This avoids having to change the interface for the existing functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM