zl程序教程

您现在的位置是:首页 >  其他

当前栏目

c语言 快速排序

语言排序 快速
2023-09-14 09:13:51 时间

文章目录

1.代码

#include "stdio.h"

//快速排序
void quickSort(int arr[],int left, int right){
    int ch[3] = {0};
    int tempLeft = left;
    int tempRight = right;
    //选取最左边的为基准元素
    int temp = arr[left];
    int compareRight = 1;
    while (left != right) {
        if (compareRight == 1) {
            //temp和右边的数比
            if(temp > arr[right]){
                arr[left] = arr[right];
                left++;
                compareRight = 0;
            }else{
                right--;
            }
        }else{
            //temp和左边的数比
            if (temp < arr[left]) {
                arr[right] = arr[left];
                right--;
                compareRight = 1;
            }else{
                left++;
            }
        }
    }
    arr[left] = temp;
    //排序基准元素左边的
    if (tempLeft < (left-1)) {
        quickSort(arr, tempLeft, left-1);
    }
    //排序基准元素右边的
    if (tempRight > left+1) {
        quickSort(arr, left+1, tempRight);
    }
 }

int main()
{
    int numArr[] = {3,5,4,6,2,45,22};
    int len = sizeof(numArr)/sizeof(int);
    quickSort(numArr,0,len-1);
    for (int i = 0; i < len; i++) {
        printf("%d\n",numArr[i]);
    }
}

打印结果:
2
3
4
5
6
22
45
Program ended with exit code: 0

2.参考博客

iOS swift 选择排序 冒泡排序 快速排序 - 我的
C语言-快速排序算法-原理-详解(完整代码)- csdn