数据结构实验之排序二:交换排序

#include <bits/stdc++.h>

using namespace std;
int cnt1,cnt2;
int Partition(int a[],int low,int high)
{
    int key = a[low];
    a[0] = a[low];
    while(low < high)//基于赋值排序时,当找到枢纽时
    {
        while(low < high&&a[high] >= key)//当某个过程中low=high时,跳出此时的while循环,执行赋值语句,此时的cnt不应该++,
        high--;                          //因为这是基于赋值的排序,当high=low时,会把low、high相互赋值,但因为是相同的数字,
        a[low] = a[high];                //不会造成结果的差异,但基于交换的排序两个值相等时不交换,所以这里多加了cnt
        //cout<<low<<" "<<high<<endl;
        if(low != high)
        cnt1++;
        while(low < high && a[low] <= key)
        low++;
        a[high] = a[low];
        //cout<<low<<" "<<high<<endl;
        if(low != high)
        cnt1++;
    }
    a[low] = key;
    return low;
}
void Qsort(int a[],int low,int high)
{
    if(low < high)
    {
        int pivotloc = Partition(a,low,high);
        Qsort(a,low,pivotloc - 1);
        Qsort(a,pivotloc + 1,high);
    }
}
void BubbleSort(int a[],int n)
{
    int i,j;
    for(i = 1;i <= n - 1;i++)
    {
        for(j = 1;j <= n - i;j++)
        {
            if(a[j] > a[j + 1])
            {
                swap(a[j],a[j + 1]);
                cnt2++;
            }
        }
    }
}
int main()
{
    int n;
    while(cin>>n)
    {
        int i,a[100006],b[100005];
        cnt1 = cnt2 = 0;
        for(i = 1;i <= n;i++)
        {
            cin>>a[i];
            b[i] = a[i];
        }
        Qsort(a,1,n);
        BubbleSort(b,n);
        /*for(i = 1;i <= n;i++)
        {
            cout<<a[i]<<" ";
        }*/
        cout<<cnt2<<" "<<cnt1;
        cout<<endl;
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值