各种排序算法

</pre><pre name="code" class="cpp">

#include<stdio.h>
int a[101];

void insertsort(int a[],int n)
{
    int i,j,temp;
    for(i=2;i<=n;i++)
    {
        if(a[i]<a[i-1])        //a[i]插入的是一个有序子表
        {
            temp=a[i];
            //循环后移
            for(j=i-1;a[j]>temp;j--)
            {
                a[j+1]=a[j];
            }
            a[j+1]=temp;
        }
    }
}
void quicksort(int left,int right)
{
    //重要!!
    if(right<left)
    return;
    int i,j,temp;
    int t;         //存放中间变量
    temp=a[left];
    i=left;j=right;
    while(i!=j)
    {
        //顺序很重要,要从右往左找
        while(a[j]>=temp&&i<j)
        j--;
        while(a[i]<=temp&&i<j)
        i++;

        if(i<j)
        {
            t=a[i];
            a[i]=a[j];
            a[j]=t;
        }
    }
    //将基数归位
    a[left]=a[i];
    a[i]=temp;

    //递归
    quicksort(left,i-1);
    quicksort(i+1,right);

    return;
}

int main()
{
    int i,n;
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    scanf("%d",&a[i]);

    insertsort(a,n);
    quicksort(1,n);   //快速排序调用

    //输出排序后的结果
    for(i=1;i<=n;i++)
    printf("%d ",a[i]);

    return 0;
}


插入排序的时间复杂度:

当最好的情况,也就是要排序的数组本身就是有序的,数组没有移动的情况,时间复杂度为o(n);最坏的情况,即待排序的数组是逆序的时间复杂度为o(n^2)。同样为o(n^2)的时间复杂度,直接插入排序比选择排序和冒泡排序的性能要好一些。


快排的时间复杂度为o(NlogN)


归并排序(MERGE-SORT)是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并。归并排序是稳定的排序,即相等的元素的顺序不会改变。

时间复杂度为O(nlogn) ,空间复杂度为O(n)。

//合并
void Merge(int sourceArr[],int tempArr[], int startIndex, int midIndex, int endIndex)
{
    int i = startIndex, j=midIndex+1, k = startIndex;
    while(i!=midIndex+1 && j!=endIndex+1)
    {
        if(sourceArr[i] >= sourceArr[j])
            tempArr[k++] = sourceArr[j++];
        else
            tempArr[k++] = sourceArr[i++];
    }
    while(i != midIndex+1)
        tempArr[k++] = sourceArr[i++];
    while(j != endIndex+1)
        tempArr[k++] = sourceArr[j++];
    for(i=startIndex; i<=endIndex; i++)
        sourceArr[i] = tempArr[i];
}
void Msort(int SR[],int TR[],int begin,int end)
{
    int m;
    //SR[]为待排数组,TR为排好数组
    if(begin==end)
    TR[begin]=SR[begin];
    else
    {
        m=(begin+end)/2;
        Msort(SR,TR,begin,m);
        Msort(SR,TR,m+1,end);
        Merge(SR,TR,begin,m,end);
    }
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值