(剑指offer)用归并排序求逆序数

#include
#include
#include
using namespace std;
int a[100] = { 7,5,6,4 };

void mergeSort(int a[],int start , int end ,int &count) {
    if (a == NULL) return;
    if (start >= end) return;
    int mid = (start + end) / 2;

    mergeSort(a,start,mid,count);
    mergeSort(a, mid+1,end,count);

    int result[100];
    int i = mid, j = end, k = end - start;
    while (i >= start && j >= mid + 1)
    {
        if (a[i] <= a[j])
        {
            
            result[k--] = a[j--];
            
        }
        else
        {
            int t = j;
            while (t >= mid + 1)
            {
                cout << "( " << a[i] << " " << a[t--] << " )\n";
                count++;
            }
            result[k--] = a[i--];
        }
            
    }
    while(i >= start)
        result[k--] = a[i--];
    while (j >= mid+1)
        result[k--] = a[j--];

    for(k = 0,i= start;i<=end;k++,i++)
        a[i] = result[k];
}


int main() {
    int count = 0;
    mergeSort(a, 0, 3,count);
    
    cout << "\n总逆序数:" << count;
    return 0;
}

你可能感兴趣的:((剑指offer)用归并排序求逆序数)