给出一组关键字序列{29,18,25,47,58,12,51,10},分别给出用希尔排序、直接选择排序和快速排序算法从小到大排序的结果。c语言
时间: 2023-09-13 16:09:44 浏览: 340
希尔排序与快速排序C语言实现
好的,我明白了。下面是三种算法的代码和排序结果:
1. 希尔排序
```c
#include <stdio.h>
void shell_sort(int arr[], int n) {
int gap, i, j, temp;
for (gap = n / 2; gap > 0; gap /= 2) {
for (i = gap; i < n; i++) {
temp = arr[i];
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
arr[j] = arr[j - gap];
}
arr[j] = temp;
}
}
}
int main() {
int arr[] = {29, 18, 25, 47, 58, 12, 51, 10};
int n = sizeof(arr) / sizeof(arr[0]);
shell_sort(arr, n);
printf("希尔排序结果:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
排序结果为:10 12 18 25 29 47 51 58
2. 直接选择排序
```c
#include <stdio.h>
void select_sort(int arr[], int n) {
int i, j, min, temp;
for (i = 0; i < n - 1; i++) {
min = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
if (min != i) {
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
}
int main() {
int arr[] = {29, 18, 25, 47, 58, 12, 51, 10};
int n = sizeof(arr) / sizeof(arr[0]);
select_sort(arr, n);
printf("直接选择排序结果:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
排序结果为:10 12 18 25 29 47 51 58
3. 快速排序
```c
#include <stdio.h>
void quick_sort(int arr[], int left, int right) {
if (left >= right) {
return;
}
int i = left, j = right, pivot = arr[left];
while (i < j) {
while (i < j && arr[j] >= pivot) {
j--;
}
arr[i] = arr[j];
while (i < j && arr[i] <= pivot) {
i++;
}
arr[j] = arr[i];
}
arr[i] = pivot;
quick_sort(arr, left, i - 1);
quick_sort(arr, i + 1, right);
}
int main() {
int arr[] = {29, 18, 25, 47, 58, 12, 51, 10};
int n = sizeof(arr) / sizeof(arr[0]);
quick_sort(arr, 0, n - 1);
printf("快速排序结果:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
排序结果为:10 12 18 25 29 47 51 58
阅读全文