先依次输入元素为整型的数个数据元素建立向量结构(数组),然后对此向量结构的元素施用直接插入排序,输出每一趟排序的结果以及最终排好序的结果;再使用折半查找排序对此向量结构进行排序输出每一趟排序结果和最后排好序的结果。用C语言实现
时间: 2024-03-21 14:41:56 浏览: 50
选择排序、插入排序、冒泡排序以及快速排序和归并排序的C语言实现,绝对可用
5星 · 资源好评率100%
好的,以下是对应的C语言代码实现:
1. 直接插入排序
```c
#include <stdio.h>
void insertionSort(int arr[], int n) {
int i, j, key;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
// 输出每一趟排序结果
printf("第%d趟排序结果:", i);
for (int k = 0; k < n; k++) {
printf("%d ", arr[k]);
}
printf("\n");
}
}
int main() {
int arr[] = {1, 5, 3, 7, 2, 9, 4, 8, 6};
int n = sizeof(arr) / sizeof(arr[0]);
printf("排序前的数组:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
insertionSort(arr, n);
printf("排序后的数组:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
2. 折半查找排序
```c
#include <stdio.h>
void binaryInsertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int left = 0, right = i - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] > key) {
// 往左边找
right = mid - 1;
} else {
// 往右边找
left = mid + 1;
}
}
for (int j = i - 1; j >= left; j--) {
arr[j + 1] = arr[j];
}
arr[left] = key;
// 输出每一趟排序结果
printf("第%d趟排序结果:", i);
for (int k = 0; k < n; k++) {
printf("%d ", arr[k]);
}
printf("\n");
}
}
int main() {
int arr[] = {1, 5, 3, 7, 2, 9, 4, 8, 6};
int n = sizeof(arr) / sizeof(arr[0]);
printf("排序前的数组:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
binaryInsertionSort(arr, n);
printf("排序后的数组:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
阅读全文