从键盘输入上述8个整数,输出快速排序和归并排序算法每一趟排序的结果。c++代码
时间: 2023-12-17 07:01:09 浏览: 138
以下是使用C代码实现快速排序和归并排序算法,并输出每一趟排序结果的示例:
```c
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
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 pivotIndex = partition(arr, low, high);
printf("快速排序第%d趟结果:", high - low + 1);
for (int i = low; i <= high; i++) {
printf("%d ", arr[i]);
}
printf("\n");
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
void merge(int arr[], int left, int middle, int right) {
int i, j, k;
int n1 = middle - left + 1;
int n2 = right - middle;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[middle + 1 + j];
i = 0;
j = 0;
k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int middle = left + (right - left) / 2;
mergeSort(arr, left, middle);
mergeSort(arr, middle + 1, right);
merge(arr, left, middle, right);
printf("归并排序第%d趟结果:", right - left + 1);
for (int i = left; i <= right; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
}
int main() {
int arr[8];
printf("请输入8个整数:\n");
for (int i = 0; i < 8; i++) {
scanf("%d", &arr[i]);
}
quickSort(arr, 0, 7);
printf("快速排序最终结果:");
for (int i = 0; i < 8; i++) {
printf("%d ", arr[i]);
}
printf("\n");
mergeSort(arr, 0, 7);
printf("归并排序最终结果:");
for (int i = 0; i < 8; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
快速排序每一趟排序的结果会以如下格式打印输出:
```
快速排序第x趟结果:a1 a2 a3 ... an
```
归并排序每一趟排序的结果会以如下格式打印输出:
```
归并排序第x趟结果:a1 a2 a3 ... an
```
快速排序和归并排序最终的结果会以如下格式打印输出:
```
快速排序最终结果:a1 a2 a3 ... an
归并排序最终结果:a1 a2 a3 ... an
```
其中,a1, a2, a3, ..., an 分别代表排序后的整数序列中的元素。
阅读全文