c语言

c语言数列排序怎样才最快

小樊
83
2024-07-16 15:00:52
栏目: 编程语言

在C语言中,使用快速排序算法是最快的数列排序方法之一。快速排序是一种基于分治思想的排序算法,它的平均时间复杂度为O(n log n),具有较高的排序效率。

以下是一个使用快速排序算法对整数数组进行排序的示例代码:

#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; 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, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);

    quickSort(arr, 0, n - 1);

    printf("Sorted array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

在上面的示例代码中,quickSort函数用于对整数数组进行快速排序,partition函数用于根据基准值将数组划分为两部分。通过递归调用quickSort函数,可以实现对整个数组的排序。您可以使用类似的算法来排序其他类型的数据。

0
看了该问题的人还看了