随机产生300个整数构成的序列,分别以直接插入、冒泡、希尔、快速、归并等排序算法排序,并统计各自的比较次数。用C语言实现
时间: 2023-07-10 19:07:29 浏览: 87
以下是用C语言实现的排序算法及比较次数统计:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int insertionSort(int arr[], int n) {
int cmp_cnt = 0;
for (int i = 1; i < n; i++) {
int tmp = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > tmp) {
arr[j + 1] = arr[j];
j--;
cmp_cnt++;
}
arr[j + 1] = tmp;
}
return cmp_cnt;
}
int bubbleSort(int arr[], int n) {
int cmp_cnt = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
cmp_cnt++;
}
}
}
return cmp_cnt;
}
int shellSort(int arr[], int n) {
int cmp_cnt = 0;
int gap = n / 2;
while (gap > 0) {
for (int i = gap; i < n; i++) {
int tmp = arr[i];
int j = i - gap;
while (j >= 0 && arr[j] > tmp) {
arr[j + gap] = arr[j];
j -= gap;
cmp_cnt++;
}
arr[j + gap] = tmp;
}
gap /= 2;
}
return cmp_cnt;
}
int quickSort(int arr[], int left, int right) {
int cmp_cnt = 0;
if (left < right) {
int pivot = arr[left];
int i = left, j = right;
while (i < j) {
while (i < j && arr[j] >= pivot) {
j--;
cmp_cnt++;
}
if (i < j) {
arr[i] = arr[j];
i++;
}
while (i < j && arr[i] < pivot) {
i++;
cmp_cnt++;
}
if (i < j) {
arr[j] = arr[i];
j--;
}
}
arr[i] = pivot;
cmp_cnt += quickSort(arr, left, i - 1);
cmp_cnt += quickSort(arr, i + 1, right);
}
return cmp_cnt;
}
void merge(int arr[], int left, int mid, int right, int tmp[]) {
int i = left, j = mid + 1, k = 0;
while (i <= mid && j <= right) {
if (arr[i] <= arr[j]) {
tmp[k++] = arr[i++];
} else {
tmp[k++] = arr[j++];
}
}
while (i <= mid) {
tmp[k++] = arr[i++];
}
while (j <= right) {
tmp[k++] = arr[j++];
}
for (i = 0; i < k; i++) {
arr[left + i] = tmp[i];
}
}
int mergeSort(int arr[], int left, int right, int tmp[]) {
int cmp_cnt = 0;
if (left < right) {
int mid = (left + right) / 2;
cmp_cnt += mergeSort(arr, left, mid, tmp);
cmp_cnt += mergeSort(arr, mid + 1, right, tmp);
merge(arr, left, mid, right, tmp);
}
return cmp_cnt;
}
int main() {
srand(time(NULL));
int n = 300;
int arr[n], tmp[n];
for (int i = 0; i < n; i++) {
arr[i] = rand();
}
int cmp_cnt;
// 直接插入排序
printf("直接插入排序:\n");
cmp_cnt = insertionSort(arr, n);
printf("比较次数:%d\n", cmp_cnt);
// 冒泡排序
printf("冒泡排序:\n");
cmp_cnt = bubbleSort(arr, n);
printf("比较次数:%d\n", cmp_cnt);
// 希尔排序
printf("希尔排序:\n");
cmp_cnt = shellSort(arr, n);
printf("比较次数:%d\n", cmp_cnt);
// 快速排序
printf("快速排序:\n");
cmp_cnt = quickSort(arr, 0, n - 1);
printf("比较次数:%d\n", cmp_cnt);
// 归并排序
printf("归并排序:\n");
cmp_cnt = mergeSort(arr, 0, n - 1, tmp);
printf("比较次数:%d\n", cmp_cnt);
return 0;
}
```
以上代码中,首先生成了一个由300个随机整数构成的数组,并分别用直接插入、冒泡、希尔、快速、归并等排序算法对这个数组进行排序,并统计比较次数。其中,直接插入排序、冒泡排序、希尔排序、快速排序、归并排序的时间复杂度分别为O(n^2)、O(n^2)、O(n^(3/2))、O(nlogn)、O(nlogn)。
阅读全文