快速排序算法

示例代码1:

//快速排序
void fun(int a[], int L, int R)
{
    if (L >= R)
        return;
    int left = L;
    int right = R;
    int temp = a[L];
    while (left < right)

    {
        while (left < right && a[right] >= temp)
            right--;
        if (left < right)
            a[left] = a[right];
        while (left < right && a[left] <= temp)
            left++;
        if (left < right)
            a[right] = a[left];
        if (left >= right)
            a[left] = temp;
    }
    fun(a, L, left);
    fun(a, left + 1, R);
}

示例代码2:

//快速排序
int quick_sort(int *arr, int low, int high)
{
    int l=low,h=high;
    if (arr == NULL)
    {
        printf("数组为空\n");
        return -1;
    }
    if (low >= high)    //递归退出条件
    {
        return 0;
    }

    int temp = arr[low]; //保存一下基准值
    while (low < high)
    {
        while (low < high && temp <= arr[high])
        { //high--比较
            high--;
        }
        arr[low] = arr[high];

        while (low < high && temp >= arr[low])
        { //low++比较
            low++;
        }
        arr[high] = arr[low];
    }
    arr[low] = temp;                //把基准值放到中轴上
    quick_sort(arr, l,  low- 1);    //中轴左半区
    quick_sort(arr, low + 1, h);    //中轴右半区
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/************************  快速排序  ************************/
#define N 10

//快速排序
void quick_sort(int *arr, int low, int high)
{
    int l = low, h = high;
    if (low >= high) //递归退出条件
        return;
    int temp = arr[low]; //保存一下基准值
    while (low < high)
    {
        while (low < high && temp <= arr[high])
            high--;
        arr[low] = arr[high];
        while (low < high && temp >= arr[low])
            low++;
        arr[high] = arr[low];
    }
    arr[low] = temp;             //把基准值放到中轴上
    quick_sort(arr, l, low - 1); //中轴左半区
    quick_sort(arr, low + 1, h); //中轴右半区
}

int main()
{
    int arr[N] = {0}, i, t; // 修改初始化为0,避免未定义的行为
    srand(time(NULL));      //在这里初始化随机数种子,只需调用一次即可
    for (i = 0; i < N; i++)
    {
        arr[i] = rand() % 100 + 1; // 在这里添加类型说明符,以明确这是整数赋值操作
    }
    printf("快排之前的:");
    for (i = 0; i < N; i++)
    {
        printf("%d ", arr[i]);
    }
    printf("\n");

    quick_sort(arr, 0, N - 1);
    printf("快排之后的:");
    for (i = 0; i < N; i++)
    {
        printf("%d ", arr[i]);
    }
    printf("\n");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值