如何编写 C 语言程序使用快速排序对数组进行排序,并附带实际示例?此快速排序程序允许用户输入数组大小和数组的行元素。接下来,我们使用嵌套 For 循环通过快速排序来对数组元素进行排序或排列。
在此示例中,我们使用 函数 和指针分离了逻辑。该函数将交换和快速排序数组元素。
#include <stdio.h>
void Swap(int *x, int *y) {
int Temp;
Temp = *x;
*x = *y;
*y = Temp;
}
void quickSort(int a[], int first, int last) {
int pivot, i, j;
if(first < last) {
pivot = first;
i = first;
j = last;
while (i < j) {
while(a[i] <= a[pivot] && i < last)
i++;
while(a[j] > a[pivot])
j--;
if(i < j) {
Swap(&a[i], &a[j]);
}
}
Swap(&a[pivot], &a[j]);
quickSort(a, first, j - 1);
quickSort(a, j + 1, last);
}
}
int main() {
int a[100], number, i;
printf("\n Please Enter the total Number of Elements : ");
scanf("%d", &number);
printf("\n Please Enter the Array Elements : ");
for(i = 0; i < number; i++)
scanf("%d", &a[i]);
quickSort(a, 0, number - 1);
printf("\n Selection Sort Result : ");
for(i = 0; i < number; i++) {
printf(" %d \t", a[i]);
}
printf("\n");
return 0;
}
请参阅 C 编程中的 C 程序、函数、指针、交换 和 数组 文章。
