#include<iostream>
#include<stack>
#include<string.h>
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)用归并排序求逆序数
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- Description In this problem, you have to analyze a partic...