快速排列序列

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string>
typedef int ElemType;
typedef struct{
    ElemType *elem;//存储元素的起始地址
    int TableLen;//元素个数
}SSTable;

void ST_Init(SSTable &ST,int len){
    ST.TableLen=len;
    ST.elem=(ElemType *) malloc(sizeof(ElemType)*ST.TableLen);//申请一块堆空间,当数组来使用
    int i;
    srand(time(NULL));//随机数生成,每一次执行代码都会得到随机的a个元素
    for(i=0;i<ST.TableLen;i++){
        ST.elem[i]=rand()%100;//生成0-99之间的随机数
    }
}

void ST_print(SSTable ST){
    for(int i=0;i<ST.TableLen;i++){
        printf("%3d",ST.elem[i]);
    }
    printf("\n");
}

void swap(int &a,int &b){
    int tmp;
    tmp=a;
    a=b;
    b=tmp;
}


//快速排列的核心
int partition(ElemType *A,int low,int high)
{
    ElemType pivot=A[low];//拿最左边的作为分割值,并储存下来
    while(low<high)
    {
        while(low<high && A[high]>=pivot)//从后往前遍历,找到一个比分割值小的
        {
            high--;
        }
        A[low]=A[high];//把比分割值小的那个元素放到A[low]
        while(low<high && A[low]<=pivot)//从前往后遍历,找到一个比分割值大的
        {
            low++;
        }
        A[high]=A[low];//把比分割值大的那个元素放到A[high]
    }
    A[low]=pivot;//把分割值放到中间位置,因为左边刚好都比它小,右边都比它大
    return low;//返回分割值现在的下标
}

//快速排列
void QuickSort(ElemType *A,int low,int high)
{
    if(low<high){
    int pivot= partition(A,low,high);
    QuickSort(A,low,pivot-1);//前一半继续递归排好
    QuickSort(A,pivot+1,high);//后一半递归排序
}
}

int main(){
    SSTable ST;
    int a;
    scanf("%d",&a);
    ST_Init(ST,a);
    ST_print(ST);
    QuickSort(ST.elem,0,a-1);
    ST_print(ST);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值