快速排序算法实现

#include <stdio.h>

//Printf the element of the array
void PrintfArray(int *Array, int front, int rear)
{
        for(int i = front; i <= rear; i++)
        {
                printf("%d\t", *(Array+i));
        }
        printf("\n");
}
//Data swap function
void Swap(int &p, int &q)
{
        int temp = p;
        p = q;
        q = temp;
}
//算法导论提供的分割算法
int Partition(int ArrayInput[], int nLow, int nHigh)
{
        int pivotkey = ArrayInput[nHigh];                 //取最后一个元素作为枢轴
        int j = nLow - 1;
        int i = nLow;

        for(; i < nHigh; i++)
        {
                if(ArrayInput[i] <= pivotkey)
                {
                        j++;                              //j指向的位置是当前大于枢轴的前一元素
                        if(i != j)
                        {
                                Swap(ArrayInput[i], ArrayInput[j]);
                        }
                }
        }
        Swap(ArrayInput[j+1], ArrayInput[nHigh]);
        return (j + 1);
}
//数据结构教材的分割算法
int Partition(int ArrayInput[], int nLow, int nHigh)
{
      int pivotkey = ArrayInput[nLow];                   //取第一个元素作为枢轴
      int i = nLow;
      int j = nHigh;
      
      while(i < j)
      {
              while((i < j) && (ArrayInput[j] >= pivotkey))
              {
                      --j;
              }
              Swap(ArrayInput[j], ArrayInput[i]);

              while((i < j) && (ArrayInput[i] <= pivotkey))
              {
                      ++i;
              }
              Swap(ArrayInput[i], ArrayInput[j]);             
      }
      return i;
}
//Quick sort
void Quick_sort(int ArrayInput[], int nLow, int nHigh)
{
        if(nLow < nHigh)
        {
                int nIndex = Partition(ArrayInput, nLow, nHigh);
                Quick_sort(ArrayInput, nLow, nIndex - 1);
                Quick_sort(ArrayInput, nIndex + 1, nHigh);
        }
}
int main()
{
        int A[50] = {5, 3, 4, 2, 6, 8, 9, 0, 1, 7,
                    21,23,25,27,30,29,22,24,26,28,
                    11,13,15,17,20,19,12,14,16,18,
                    58,56,54,52,59,60,57,55,53,51,
                    71,73,75,77,80,79,72,74,76,78};
        int  Arraylen = sizeof(A)/sizeof(int);

        PrintfArray(A, 0, Arraylen - 1);

        Quick_sort(A, 0, Arraylen - 1);

        printf("after Quick_sort:\n");
        PrintfArray(A, 0, Arraylen - 1);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值