用c语言写出比较归并排序和快速排序的关键字比较次数和关键字移动次数的代码,要求待排序的表长不能小于100;其中的数据要用伪随机数生成程序产生至少要用5组不同的输入数据比较
时间: 2023-12-20 22:05:31 浏览: 80
以下是用C语言实现比较归并排序和快速排序的代码,并计算关键字比较次数和关键字移动次数,同时使用伪随机数生成程序产生5组不同的输入数据进行比较:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void merge(int arr[], int l, int m, int r, int* comp, int* move)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
(*comp)++;
if (L[i] <= R[j]) {
arr[k] = L[i];
(*move)++;
i++;
}
else {
arr[k] = R[j];
(*move)++;
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
(*move)++;
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
(*move)++;
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r, int* comp, int* move)
{
if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m, comp, move);
mergeSort(arr, m + 1, r, comp, move);
merge(arr, l, m, r, comp, move);
}
}
void swap(int* a, int* b, int* move)
{
int t = *a;
*a = *b;
*b = t;
(*move)++;
}
int partition(int arr[], int low, int high, int* comp, int* move)
{
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
(*comp)++;
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j], move);
}
}
swap(&arr[i + 1], &arr[high], move);
return (i + 1);
}
void quickSort(int arr[], int low, int high, int* comp, int* move)
{
if (low < high) {
int pi = partition(arr, low, high, comp, move);
quickSort(arr, low, pi - 1, comp, move);
quickSort(arr, pi + 1, high, comp, move);
}
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main()
{
srand(time(NULL));
int n = 100;
int comp, move;
for (int i = 0; i < 5; i++) {
printf("Input %d:\n", i + 1);
int arr[n];
for (int j = 0; j < n; j++)
arr[j] = rand() % 1000;
comp = move = 0;
mergeSort(arr, 0, n - 1, &comp, &move);
printf("After Merge Sort:\n");
printArray(arr, n);
printf("Number of comparisons: %d\n", comp);
printf("Number of moves: %d\n", move);
comp = move = 0;
quickSort(arr, 0, n - 1, &comp, &move);
printf("After Quick Sort:\n");
printArray(arr, n);
printf("Number of comparisons: %d\n", comp);
printf("Number of moves: %d\n", move);
printf("\n");
}
return 0;
}
```
注意:以上代码中使用了伪随机数生成程序产生5组不同的输入数据进行比较,每次运行结果可能会有所不同。
阅读全文