#include<iostream>
#include<stdio.h>
using namespace std;
int st[1000010];
long long sum;
void merge(int e1,int t1,int e2,int t2)
{
int* ne=new int[t2-e1+5];
int fl=0,i;
int m=e1,n=e2;
while(m<=t1&&n<=t2)
{
if(st[m]<=st[n])
{
ne[fl++]=st[m++];
continue;
}
else
{
ne[fl++]=st[n++];
sum+=t1-m+1;
continue;
}
} //cout<<"fdsaf"<<endl;
while(m<=t1) ne[fl++]=st[m++];
while(n<=t2) ne[fl++]=st[n++];
for(i=e1;i<=t2;i++)
st[i]=ne[i-e1];
delete ne;
}
void sortmerge(int s,int t)
{
int m;
if(s<t)
{
m=(s+t)/2;
sortmerge(s,m);
sortmerge(m+1,t);
merge(s,m,m+1,t);
}
}
int main()
{
int a;
scanf("%d",&a);
while(a--)
{
int i,n;
sum=0;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&st[i]);
sortmerge(0,n-1);
printf("%lld\n",sum);
}
return 0;
}
归并,百度百科:
#include <stdlib.h>
#include <stdio.h>
void Merge(int sourceArr[],int tempArr[], int startIndex, int midIndex, int endIndex)
{
int i = startIndex, j=midIndex+1, k = startIndex;
while(i!=midIndex+1 && j!=endIndex+1)
{
if(sourceArr[i] > sourceArr[j])
tempArr[k++] = sourceArr[j++];
else
tempArr[k++] = sourceArr[i++];
}
while(i != midIndex+1)
tempArr[k++] = sourceArr[i++];
while(j != endIndex+1)
tempArr[k++] = sourceArr[j++];
for(i=startIndex; i<=endIndex; i++)
sourceArr[i] = tempArr[i];
}
//内部使用递归
void MergeSort(int sourceArr[], int tempArr[], int startIndex, int endIndex)
{
int midIndex;
if(startIndex < endIndex)
{
midIndex = (startIndex + endIndex) / 2;
MergeSort(sourceArr, tempArr, startIndex, midIndex);
MergeSort(sourceArr, tempArr, midIndex+1, endIndex);
Merge(sourceArr, tempArr, startIndex, midIndex, endIndex);
}
}
int main(int argc, char * argv[])
{
int a[8] = {50, 10, 20, 30, 70, 40, 80, 60};
int i, b[8];
MergeSort(a, b, 0, 7);
for(i=0; i<8; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
快排:
void sort(int *a, int left, int right)
{
if(left >= right)/*如果左边索引大于或者等于右边的索引就代表已经整理完成一个组了*/
{
return ;
}
int i = left;
int j = right;
int key = a[left];
while(i < j) /*控制在当组内寻找一遍*/
{
while(i < j && key <= a[j])
/*而寻找结束的条件就是,1,找到一个小于或者大于key的数(大于或小于取决于你想升
序还是降序)2,没有符合条件1的,并且i与j的大小没有反转*/
{
j--;/*向前寻找*/
}
if (i < j) {
a[i] = a[j];
i ++;
}
/*找到一个这样的数后就把它赋给前面的被拿走的i的值(如果第一次循环且key是
a[left],那么就是给key)*/
while(i < j && key >= a[i])
/*这是i在当组内向前寻找,同上,不过注意与key的大小关系停止循环和上面相反,
因为排序思想是把数往两边扔,所以左右两边的数大小与key的关系相反*/
{
i++;
}
if (i < j) {
a[j] = a[i];
j++;
}
}
a[i] = key;/*当在当组内找完一遍以后就把中间数key回归*/
sort(a, left, i - 1);/*最后用同样的方式对分出来的左边的小组进行同上的做法*/
sort(a, i + 1, right);/*用同样的方式对分出来的右边的小组进行同上的做法*/
/*当然最后可能会出现很多分左右,直到每一组的i = j 为止*/
}