用c语言写一个时间复杂度为nlogn的简易代码
时间: 2024-09-15 15:10:57 浏览: 47
在 C 语言中,我们可以使用快速排序算法来编写一个时间复杂度为 O(n log n) 的简单代码。快速排序是一种常用的分治算法,其基本思想是通过一趟排序将待排记录分隔成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,然后分别对这两部分记录继续进行排序。
下面是一个简单的快速排序 C 语言实现:
```c
#include <stdio.h>
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
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++; // 交换arr[i]和arr[j]
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[] = {9, 7, 5, 11, 12, 2, 14, 3, 10};
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]);
printf("\n");
return 0;
}
```
阅读全文
相关推荐


















