随机产生300个整数构成的序列,分别以直接插入、冒泡、希尔、快速、、归并等排序算法排序,并统计各自的比较次数用c编写
时间: 2023-10-20 13:14:47 浏览: 86
以下是C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 直接插入排序
int insert_sort(int arr[], int n) {
int i, j, key, count = 0;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
count++;
}
arr[j + 1] = key;
}
return count;
}
// 冒泡排序
int bubble_sort(int arr[], int n) {
int i, j, tmp, count = 0;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
count++;
}
}
}
return count;
}
// 希尔排序
int shell_sort(int arr[], int n) {
int i, j, gap, tmp, count = 0;
for (gap = n / 2; gap > 0; gap /= 2) {
for (i = gap; i < n; i++) {
for (j = i - gap; j >= 0 && arr[j] > arr[j + gap]; j -= gap) {
tmp = arr[j];
arr[j] = arr[j + gap];
arr[j + gap] = tmp;
count++;
}
}
}
return count;
}
// 快速排序
int quick_sort(int arr[], int left, int right) {
int i, j, pivot, tmp, count = 0;
if (left < right) {
pivot = arr[left];
i = left;
j = right + 1;
while (1) {
do {
i++;
count++;
} while (arr[i] < pivot);
do {
j--;
count++;
} while (arr[j] > pivot);
if (i >= j) {
break;
}
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
tmp = arr[left];
arr[left] = arr[j];
arr[j] = tmp;
count += quick_sort(arr, left, j - 1);
count += quick_sort(arr, j + 1, right);
}
return count;
}
// 归并排序
void merge(int arr[], int left, int mid, int right, int tmp[], int *count) {
int i = left, j = mid + 1, k = 0;
while (i <= mid && j <= right) {
if (arr[i] <= arr[j]) {
tmp[k++] = arr[i++];
(*count)++;
} else {
tmp[k++] = arr[j++];
(*count)++;
}
}
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];
}
}
void merge_sort(int arr[], int left, int right, int tmp[], int *count) {
if (left < right) {
int mid = (left + right) / 2;
merge_sort(arr, left, mid, tmp, count);
merge_sort(arr, mid + 1, right, tmp, count);
merge(arr, left, mid, right, tmp, count);
}
}
int main() {
int arr[300], tmp[300];
int i, n = sizeof(arr) / sizeof(int);
srand(time(NULL));
for (i = 0; i < n; i++) {
arr[i] = rand() % 1000;
}
printf("排序前:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
int count_insert = insert_sort(arr, n);
printf("直接插入排序比较次数:%d\n", count_insert);
int count_bubble = bubble_sort(arr, n);
printf("冒泡排序比较次数:%d\n", count_bubble);
int count_shell = shell_sort(arr, n);
printf("希尔排序比较次数:%d\n", count_shell);
int count_quick = quick_sort(arr, 0, n - 1);
printf("快速排序比较次数:%d\n", count_quick);
int count_merge = 0;
merge_sort(arr, 0, n - 1, tmp, &count_merge);
printf("归并排序比较次数:%d\n", count_merge);
printf("排序后:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
阅读全文