用C语言能对n个整数进行排序的函数
时间: 2024-11-03 21:15:41 浏览: 25
在C语言中,你可以使用多种算法对n个整数进行排序,其中一种常见的选择是快速排序(Quick Sort)。这是一种分治策略的排序算法,基本思想是选择一个基准值(pivot),将数组分为两部分,一部分的所有元素都小于基准,另一部分所有元素都大于或等于基准,然后递归地对这两部分进行同样的操作。
下面是一个简单的快速排序函数示例:
```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); // Index of smaller element
for (int j = low; j <= high- 1; j++) {
if (arr[j] < pivot) {
i++; // increment index of smaller element
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);
}
}
// Function to print an array
void printArray(int arr[], int size) {
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {9, 7, 5, 11, 12, 2, 14, 3, 10, 6};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Original array: \n");
printArray(arr, n);
quickSort(arr, 0, n-1);
printf("\nSorted array: \n");
printArray(arr, n);
return 0;
}
```
这个程序首先定义了`swap`、`partition`和`quickSort`三个辅助函数,最后在`main`函数里创建了一个数组并调用了快速排序对其进行排序。
阅读全文
相关推荐


















