归并排序--小白写的

归并排序
    排序算法,最好实现的一种算法之一啊。学习该算法只需要了解递归就好了。首先给出一个问题,给出两个有序的数列,让你把它合成一个有序的数列,那么我们只需要两个同时从前往后看,小的数放到一个临时数组(当然这样是从小到大的排序),这样这个数组里面就是一个有序的了。然后再把这个有序的数组放回原来的位置。所以,会递归,归并排序写起来就很简单了。
#include <cstdio>
#include <cstring>
#include <cctype>
#include <cmath>
#include <set>
#include <map>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stdlib.h>
#include <time.h>
using namespace std;
typedef long long LL;
const int INF=2e9+1e8;

const int MOD=1e9+7;
const int MAXSIZE=1e6+5;
const double eps=0.0000000001;
void fre()
{
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
}
#define memst(a,b) memset(a,b,sizeof(a))
#define fr(i,a,n) for(int i=a;i<n;i++)


int arr[MAXSIZE],temp[MAXSIZE];
LL ans;


void mergearr(int first,int mid,int last)
{
    int i=first,j=mid+1,k=0;
    while(i<=mid&&j<=last)
    {
        if(arr[i]<arr[j]) temp[k++]=arr[i++];
        else temp[k++]=arr[j++];
    }
    while(i<=mid) temp[k++]=arr[i++];
    while(j<=last) temp[k++]=arr[j++];
    j=0;
    for(i=first;i<=last;i++,j++) arr[i]=temp[j];
}

void mergesort(int first,int last)
{
    int mid=(first+last)/2;
    if(first<last)
    {
        mergesort(first,mid);
        mergesort(1+mid,last);
        mergearr(first,mid,last);
    }
}
void show(int n)
{
    for(int i=0;i<n;i++)
        printf("%d ",arr[i]);
    printf("\n");
}
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=0;i<n;i++) scanf("%d",&arr[i]);
        mergesort(0,n-1);
        show(n);
    }
	return 0;
}

/**************************************************/
/**             Copyright Notice                 **/
/**  writer: wurong                              **/
/**  school: nyist                               **/
/**  blog  : http://blog.csdn.net/wr_technology  **/
/**************************************************/




 这题目刚好练练手,逆序数。





posted @ 2017-03-13 16:21  Code-dream  阅读(162)  评论(0编辑  收藏  举报