对随机产生的1000个整数构成的序列分别进行直接插入、冒泡、希尔、快速、归并排序,并统计各自的比较次数。用C语言编写上述代码
时间: 2023-08-06 15:10:07 浏览: 153
好的,以下是C语言的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 直接插入排序
int insertSort(int arr[], int n) {
int i, j, temp, count = 0;
for (i = 1; i < n; i++) {
temp = arr[i];
for (j = i - 1; j >= 0 && temp < arr[j]; j--) {
arr[j + 1] = arr[j];
count++;
}
arr[j + 1] = temp;
}
return count;
}
// 冒泡排序
int bubbleSort(int arr[], int n) {
int i, j, temp, count = 0;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
count++;
}
}
}
return count;
}
// 希尔排序
int shellSort(int arr[], int n) {
int i, j, gap, temp, count = 0;
for (gap = n / 2; gap > 0; gap /= 2) {
for (i = gap; i < n; i++) {
temp = arr[i];
for (j = i - gap; j >= 0 && temp < arr[j]; j -= gap) {
arr[j + gap] = arr[j];
count++;
}
arr[j + gap] = temp;
}
}
return count;
}
// 快速排序
int quickSort(int arr[], int left, int right) {
int i, j, temp, count = 0;
if (left < right) {
i = left;
j = right;
temp = arr[left];
while (i < j) {
while (i < j && arr[j] >= temp) {
j--;
count++;
}
if (i < j) {
arr[i++] = arr[j];
count++;
}
while (i < j && arr[i] < temp) {
i++;
count++;
}
if (i < j) {
arr[j--] = arr[i];
count++;
}
}
arr[i] = temp;
count += quickSort(arr, left, i - 1);
count += quickSort(arr, i + 1, right);
}
return count;
}
// 归并排序
int merge(int arr[], int left, int mid, int right) {
int i, j, k, count = 0;
int *temp = (int *)malloc(sizeof(int) * (right - left + 1));
i = left;
j = mid + 1;
k = 0;
while (i <= mid && j <= right) {
if (arr[i] < arr[j]) {
temp[k++] = arr[i++];
count++;
} else {
temp[k++] = arr[j++];
count++;
}
}
while (i <= mid) {
temp[k++] = arr[i++];
count++;
}
while (j <= right) {
temp[k++] = arr[j++];
count++;
}
for (i = left, k = 0; i <= right; i++, k++) {
arr[i] = temp[k];
}
free(temp);
return count;
}
int mergeSort(int arr[], int left, int right) {
int count = 0;
if (left < right) {
int mid = (left + right) / 2;
count += mergeSort(arr, left, mid);
count += mergeSort(arr, mid + 1, right);
count += merge(arr, left, mid, right);
}
return count;
}
int main() {
// 生成随机数列
int n = 1000;
int arr[n];
srand(time(NULL));
for (int i = 0; i < n; i++) {
arr[i] = rand() % 10000;
}
// 直接插入排序
int count1 = insertSort(arr, n);
printf("直接插入排序:比较次数=%d\n", count1);
// 冒泡排序
int count2 = bubbleSort(arr, n);
printf("冒泡排序:比较次数=%d\n", count2);
// 希尔排序
int count3 = shellSort(arr, n);
printf("希尔排序:比较次数=%d\n", count3);
// 快速排序
int count4 = quickSort(arr, 0, n - 1);
printf("快速排序:比较次数=%d\n", count4);
// 归并排序
int count5 = mergeSort(arr, 0, n - 1);
printf("归并排序:比较次数=%d\n", count5);
return 0;
}
```
这里我们利用了不同排序算法的函数来实现对随机数列的排序,并统计了不同算法的比较次数。
阅读全文