码迷,mamicode.com
首页 > 编程语言 > 详细

归并排序 堆排序

时间:2014-10-29 21:27:25      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   ar   for   sp   div   

1、归并排序

#include "stdafx.h"
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#define maxn 111111
using namespace std;
int n, a[maxn], b[maxn];
void mergesort(int ll, int rr)
{
    if (ll == rr) { b[ll] = a[ll]; return; }
    mergesort(ll, (ll + rr) / 2);
    mergesort((ll + rr) / 2 + 1, rr);
    int p1 = ll, p2 = (ll + rr) / 2 + 1, cnt = ll;
    while (p1 <= (ll + rr) / 2 && p2 <= rr)
    {
        if (b[p1] < b[p2]) { a[cnt++] = b[p1]; p1++; }
        else { a[cnt++] = b[p2]; p2++; }
    }
    while (p1 <= (ll + rr) / 2)
    {
        a[cnt++] = b[p1];
        p1++;
    }
    while (p2 <= rr)
    {
        a[cnt++] = b[p2];
        p2++;
    }
    for (int i = ll; i <= rr; i++) b[i] = a[i];    
}
int _tmain(int argc, _TCHAR* argv[])
{
    scanf("%d", &n);
    for (int i = 0; i < n; i++) scanf("%d", &a[i]);
    mergesort(0, n - 1);
    for (int i = 0; i < n; i++) printf("%d ", b[i]);
    printf("\n");
    return 0;
}

2、堆排序

#include "stdafx.h"
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#define maxn 1111111
using namespace std;
int n, a[maxn];
void pushdown(int x)
{
    while (x * 2 +1< n)
    {
        int j = 1;
        if (x*2+2<n && a[x * 2 + 2] < a[x * 2 + 1]) j = 2;
        if (a[x]>a[x * 2 + j]) swap(a[x], a[x * 2 + j]); else break;
        x = x * 2 + j;
    }
}
int _tmain(int argc, _TCHAR* argv[])
{
    scanf("%d", &n);
    for (int i = 0; i < n; i++) scanf("%d", &a[i]);
    for (int i = (n - 1) / 2; i >= 0;i--) pushdown(i);
    int cnt = n;
    for (int i = 0; i < cnt; i++)
    {
        printf("%d ", a[0]);
        swap(a[0], a[--n]);
        pushdown(0);
    }
    return 0;
}

 

归并排序 堆排序

标签:style   blog   io   color   os   ar   for   sp   div   

原文地址:http://www.cnblogs.com/strawberryfgalois/p/4060511.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!