常用排序算法

常用排序算法,第1张

1.冒泡排序
void BubbleSort(int a[],int len)
{int tmp;
    for (int i=0; i<n-1; i++)
    {
        int flag = FALSE;
        for(int j=n-1;j>i;j--)
            if(a[j-1]>a[j])
            {
                tmp = a[j-1];
                a[j-1] = a[j];
                a[j] = tmp;
                flag = TRUE;
            }
        if(flag == FALSE)
            return;
    }
}
2.简单选择排序
void SelectSort(int a[],int len)
{int tmp;
    for(int i=0; i<n-1; i++)
    {
        int min = i;
        for(j=i+1; j<len; j++)
            if(a[j]<a[min]) 
                min=j;
        if(min!=i)
        {
            tmp = a[min];
            a[min] = a[i];
            a[i]=tmp;
        }
    }
}
3.快速排序
void QuickSort(int a[],int low,int high)
{
    if(low<high)
    {
        int pivotpos = Partition(a,low,high);//枢轴
        QuickSort(a,low,pivotpos-1);
        QuickSort(a,pivotpos+1,high);
    }
}
int Partition(int a[],int low,int high)
{   //一趟划分 *** 作
    int pivot = a[low];
    while(low<high)
    {
        while(low<high && a[high]>=pivot) --high;
        a[low]=a[high];
        while(low<high && a[high]<=pivot) ++low;
        a[high]=a[low];
    }
    a[low]=pivot;
    return low;
}
4.堆排序
void HeadAdjust(int a[],int k,int len)
{   //将元素k为根的子树进行调整
    a[0]=a[k];
    for(int i=2*k; i<=len; i*=2)
    {
        if(i<len&&a[i]<a[i+1])
            i++;
        if(a[0]>=a[i])
            break;
        else
        {
            a[k]=a[i];
            k=i;
        }
    }
    a[k]=a[0];
}

void BuildMaxHeap(int a[],int len)
{
    for(int i=len/2; i>0; i--)//i从[n/2]到1,反复调整堆
        HeadAdjust(a,i,len);
}

void HeapSort(int a[],int len)
{
    int tmp;
    BuildMaxHeap(a,len);
    for (int i=len; i>1; i--)
    {
        tmp = a[i];
        a[i] = a[1];
        a[1]=tmp;
        HeadAdjust(a,1,i-1);
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/873029.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存