排序算法汇总二------交换类算法

本文介绍了两种经典的排序算法——冒泡排序和快速排序的具体实现方法,并提供了完整的C++代码示例。通过对比两种算法的工作原理及效率,帮助读者更好地理解它们的应用场景。

冒泡排序:

void BubbleSort(int *d,int length)
{
    bool finish=false;
    for(int i=1;i<=length-1&&!finish;i++)
    {
        finish=true;
        for(int j=0;j<length-i;j++)
        {
            if(d[j]<d[j+1])
            {
                int x=d[j];
                d[j]=d[j+1];
                d[j+1]=x;
                finish=false;
            }
        }
    }
    Print(d,length);
}


快速排序:


int QKPass(int *d,int low,int high)
{
    int now=d[low];
    while(low<high){
        while(low<high && d[high]>=now){high--;}
        if(low<high){d[low]=d[high];low++;}
        while(low<high && d[low]<now){low++;}
        if(low<high){d[high]=d[low];high--;}
    }
    d[low]=now;
    return low;
}
void QKSort(int *d,int low,int high)
{
    if(low<high)
    {
        int ans=QKPass(d,low,high);
        QKSort(d,low,ans-1);
        QKSort(d,ans+1,high);
    }
}

总的测试代码:

#include<iostream>
#include<cstdio>
#include<algorithm>

using namespace std;
using namespace std;
int data[10]={0,5,6,9,8,7,5,3,5,1};//test data
void Print(int *d,int length)
{
    for(int i=0;i<length;i++)
    {
        printf("%d ",d[i]);
    }
    printf("\n\n\n");
}
void BubbleSort(int *d,int length)
{
    bool finish=false;
    for(int i=1;i<=length-1&&!finish;i++)
    {
        finish=true;
        for(int j=0;j<length-i;j++)
        {
            if(d[j]<d[j+1])
            {
                int x=d[j];
                d[j]=d[j+1];
                d[j+1]=x;
                finish=false;
            }
        }
    }
    Print(d,length);
}
int QKPass(int *d,int low,int high)
{
    int now=d[low];
    while(low<high){
        while(low<high && d[high]>=now){high--;}
        if(low<high){d[low]=d[high];low++;}
        while(low<high && d[low]<now){low++;}
        if(low<high){d[high]=d[low];high--;}
    }
    d[low]=now;
    return low;
}
void QKSort(int *d,int low,int high)
{
    if(low<high)
    {
        int ans=QKPass(d,low,high);
        QKSort(d,low,ans-1);
        QKSort(d,ans+1,high);
    }
}

int main()
{
    QKSort(data,0,9);
    Print(data,10);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值