快速排序QuickSort.c

本文介绍了一个使用C语言实现的快速排序算法。通过递归方式,该算法能够有效地对整型数组进行排序。用户可以输入任意数量的整数,程序将对其进行排序并输出排序后的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>

int sorted(int a[],int low,int high){
    int temp=0;
    int sign=a[low];
    while(low<high){
        while(low<high && sign<a[high])
            --high;
        temp=a[high];
        a[high]=a[low];
        a[low]=temp;
       
        while(low<high && a[low]<sign)
            ++low;
        temp=a[low];
        a[low]=a[high];
        a[high]=temp;
    }
    return low;
}

void sort(int a[],int low,int high){
    int sign=0;
    if(low<high){
        sign=sorted(a,low,high);
        sort(a,low,sign-1);
        sort(a,sign+1,high);
    }
}

void main()
{
    int a[20];
    int i=0;
    int count=0;
    printf("count= ");
    scanf("%d",&count);
    for(i=0;i<count;i++){
        printf("a[%d]=",i);
        scanf("%d",&a[i]);
    }
    sort(a,0,count-1);
    printf("/nThe sorted numbers:/n");
    for(i=0;i<count;i++)
        printf("%d ",a[i]);
    printf("/nSort Work Is OK!/n/n");
    getchar();
}

快速排序是一种常用的排序算法,其核心思想是通过选择一个基准元素,将待排序序列分成两个子序列,小于基准的在左边,大于基准的在右边,然后对子序列分别进行递归排序,最终得到有序序列。 在C语言中,我们可以使用以下的代码来实现快速排序: ```c #include <stdio.h> // 交换两个元素的值 void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } // 寻找基准元素的位置,并返回 int partition(int arr[], int low, int high) { int pivot = arr[high]; // 选择最后一个元素为基准 int i = (low - 1); for (int j = low; j <= high - 1; j++) { if (arr[j] < pivot) { i++; swap(&arr[i], &arr[j]); // 将小于基准的元素放到左边 } } swap(&arr[i + 1], &arr[high]); // 将基准元素放到正确的位置 return (i + 1); } // 快速排序函数 void quickSort(int arr[], int low, int high) { if (low < high) { int pi = partition(arr, low, high); // 找到基准元素的位置 quickSort(arr, low, pi - 1); // 对左边子序列进行递归排序 quickSort(arr, pi + 1, high); // 对右边子序列进行递归排序 } } // 主函数 int main() { int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr) / sizeof(arr[0]); quickSort(arr, 0, n - 1); printf("排序结果:"); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; } ``` 以上的代码首先定义了一个交换函数`swap`,用于交换两个元素的值。接下来,定义了一个寻找基准元素位置的函数`partition`,通过选择最后一个元素作为基准,将小于基准的元素放到左边,大于基准的元素放到右边,并返回基准元素的位置。 最后,定义了快速排序函数`quickSort`,首先通过`partition`函数找到基准元素的位置,然后递归地对基准元素左边的子序列和右边的子序列进行排序。 在主函数中,先定义一个待排序的数组`arr`,然后通过`quickSort`函数对其进行排序。最后,输出排序结果。 快速排序的时间复杂度为O(nlogn),是一种高效的排序算法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值