排序之——排序的交换次序

数据结构实验之排序二:交换排序
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic
Problem Description
冒泡排序和快速排序都是基于"交换"进行的排序方法,你的任务是对题目给定的N个(长整型范围内的)整数从小到大排序,输出用冒泡和快排对这N个数排序分别需要进行的数据交换次数。

Input
连续多组输入数据,每组数据第一行给出正整数N(N ≤ 10^5),随后给出N个整数,数字间以空格分隔。

Output
输出数据占一行,代表冒泡排序和快速排序进行排序分别需要的交换次数,数字间以1个空格分隔,行末不得有多余空格。

Example Input
8
49 38 65 97 76 13 27 49
Example Output
15 9

#include<iostream>
#include<cstring>
#include<algorithm>
#include<stdio.h>
using namespace std;

const int N=100010;

long int q[N];
long int tmp[N];
long int sum_quick, sum_bubble;
long int n;

long int bubble_sort(long int tmp[])
{
    for(int i=0;i<n;i++)
        for(int j=i+1;j<n;j++)
        {
            if(tmp[i]>tmp[j])
            {
                swap(tmp[i],tmp[j]);
                sum_bubble++;
            }
        }
    return sum_bubble;
}

long int  quick_sort(long int q[], int l, int r)
{
    if(l>=r) return sum_quick;
    //这是标准的快排
    int i=l, j=r, x=q[l];
    while(i<j)
    {
        while(i<j && q[j]>=x) j--;
        if(i!=j) sum_quick++;//这个快排模板有个问题,就是当i与j相等时,仍然会swap,所以在求交换次数时,必须对这种情况做限制
        swap(q[j],q[i]);
        while(i<j && q[i]<=x) i++;
        if(i!=j) sum_quick++;
        swap(q[i],q[j]);
    }

    quick_sort(q, l, i-1);
    quick_sort(q, i+1, r);

    return sum_quick;
}

int main()
{

    while(scanf("%d",&n)!=EOF)
    {
    sum_bubble=sum_quick=0;//这里要注意的是全局变量与局部变量的问题
    for(int i=0;i<n;i++) cin>>q[i];

    memcpy(tmp, q, sizeof q);

    sum_bubble=bubble_sort(tmp);
    cout<<sum_bubble<<' ';

    sum_quick=quick_sort(q, 0, n-1);
    cout<<sum_quick<<endl;
    }

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值