使用冒泡法和快速排序法对给定序列排序的c语言程序
时间: 2023-07-02 16:23:19 浏览: 104
冒泡排序的C语言程序:
```c
#include <stdio.h>
void bubble_sort(int arr[], int len) {
int i, j, temp;
for (i = 0; i < len - 1; i++) {
for (j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = {5, 2, 8, 4, 6, 1, 3, 9, 7};
int len = sizeof(arr) / sizeof(int);
bubble_sort(arr, len);
for (int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
快速排序的C语言程序:
```c
#include <stdio.h>
int partition(int arr[], int low, int high) {
int pivot = arr[low];
while (low < high) {
while (low < high && arr[high] >= pivot) {
high--;
}
arr[low] = arr[high];
while (low < high && arr[low] <= pivot) {
low++;
}
arr[high] = arr[low];
}
arr[low] = pivot;
return low;
}
void quick_sort(int arr[], int low, int high) {
if (low < high) {
int pivot_pos = partition(arr, low, high);
quick_sort(arr, low, pivot_pos - 1);
quick_sort(arr, pivot_pos + 1, high);
}
}
int main() {
int arr[] = {5, 2, 8, 4, 6, 1, 3, 9, 7};
int len = sizeof(arr) / sizeof(int);
quick_sort(arr, 0, len - 1);
for (int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
阅读全文