编写一个c语言代码,内容是使用冒泡法或快速排序法对给定序列排序(递归/非递归两种方法)
时间: 2024-02-28 12:55:16 浏览: 68
以下是使用冒泡排序法对给定序列排序的非递归方法的C语言代码:
```c
#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("排序后的序列:\n");
for (int i=0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
以下是使用快速排序法对给定序列排序的递归方法的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++;
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("排序后的序列:\n");
for (int i=0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
阅读全文