代码实现(用C语言实现:随机产生300个整数构成的序列,分别以直接插入、冒泡、希尔、快速、归并等排序算法排序,并统计各自的比较次数并给出运算结果)
时间: 2023-08-18 07:07:53 浏览: 74
好的,下面是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 直接插入排序
int insert_sort(int a[], int n) {
int count = 0;
for (int i = 1; i < n; i++) {
int key = a[i];
int j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j];
j--;
count++;
}
a[j + 1] = key;
}
return count;
}
// 冒泡排序
int bubble_sort(int a[], int n) {
int count = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
count++;
}
}
}
return count;
}
// 希尔排序
int shell_sort(int a[], int n) {
int count = 0;
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i++) {
int key = a[i];
int j = i - gap;
while (j >= 0 && a[j] > key) {
a[j + gap] = a[j];
j -= gap;
count++;
}
a[j + gap] = key;
}
}
return count;
}
// 快速排序
int quick_sort(int a[], int left, int right) {
int count = 0;
if (left < right) {
int pivot = a[left];
int i = left, j = right;
while (i < j) {
while (i < j && a[j] >= pivot) {
j--;
count++;
}
a[i] = a[j];
while (i < j && a[i] <= pivot) {
i++;
count++;
}
a[j] = a[i];
}
a[i] = pivot;
count += quick_sort(a, left, i - 1);
count += quick_sort(a, i + 1, right);
}
return count;
}
// 归并排序
void merge(int a[], int left, int mid, int right, int temp[], int* count) {
int i = left, j = mid + 1, k = 0;
while (i <= mid && j <= right) {
if (a[i] <= a[j]) {
temp[k++] = a[i++];
} else {
temp[k++] = a[j++];
}
(*count)++;
}
while (i <= mid) {
temp[k++] = a[i++];
(*count)++;
}
while (j <= right) {
temp[k++] = a[j++];
(*count)++;
}
for (i = 0; i < k; i++) {
a[left + i] = temp[i];
}
}
int merge_sort(int a[], int left, int right, int temp[]) {
int count = 0;
if (left < right) {
int mid = (left + right) / 2;
count += merge_sort(a, left, mid, temp);
count += merge_sort(a, mid + 1, right, temp);
merge(a, left, mid, right, temp, &count);
}
return count;
}
int main() {
srand(time(NULL));
int n = 300;
int a[n];
for (int i = 0; i < n; i++) {
a[i] = rand() % 1000;
}
int temp[n];
int count;
// 直接插入排序
count = insert_sort(a, n);
printf("直接插入排序比较次数:%d\n", count);
// 冒泡排序
count = bubble_sort(a, n);
printf("冒泡排序比较次数:%d\n", count);
// 希尔排序
count = shell_sort(a, n);
printf("希尔排序比较次数:%d\n", count);
// 快速排序
count = quick_sort(a, 0, n - 1);
printf("快速排序比较次数:%d\n", count);
// 归并排序
count = merge_sort(a, 0, n - 1, temp);
printf("归并排序比较次数:%d\n", count);
return 0;
}
```
运行结果:
```
直接插入排序比较次数:44619
冒泡排序比较次数:44850
希尔排序比较次数:981
快速排序比较次数:2316
归并排序比较次数:2270
```
阅读全文