随机产生300个整数构成的序列,分别以直接插入、冒泡、希尔、快速、归并排序,统计各自比较次数。c语言
时间: 2023-12-21 17:03:45 浏览: 84
以下是C语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXSIZE 300 // 序列最大长度
// 直接插入排序
int InsertionSort(int A[], int n) {
int cnt = 0;
for (int i = 1; i < n; i++) {
int temp = A[i];
int j = i - 1;
while (j >= 0 && A[j] > temp) {
cnt++;
A[j + 1] = A[j];
j--;
}
cnt++;
A[j + 1] = temp;
}
return cnt;
}
// 冒泡排序
int BubbleSort(int A[], int n) {
int cnt = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
cnt++;
if (A[j] > A[j + 1]) {
int temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
}
}
}
return cnt;
}
// 希尔排序
int ShellSort(int A[], int n) {
int cnt = 0;
int gap = n / 2;
while (gap > 0) {
for (int i = gap; i < n; i++) {
int temp = A[i];
int j = i - gap;
while (j >= 0 && A[j] > temp) {
cnt++;
A[j + gap] = A[j];
j -= gap;
}
cnt++;
A[j + gap] = temp;
}
gap /= 2;
}
return cnt;
}
// 快速排序
void QuickSort(int A[], int low, int high, int *cnt) {
if (low >= high) return;
int i = low, j = high, pivot = A[low];
while (i < j) {
while (i < j && A[j] >= pivot) {
(*cnt)++;
j--;
}
A[i] = A[j];
while (i < j && A[i] <= pivot) {
(*cnt)++;
i++;
}
A[j] = A[i];
}
A[i] = pivot;
QuickSort(A, low, i - 1, cnt);
QuickSort(A, i + 1, high, cnt);
}
// 归并排序
void Merge(int A[], int L1, int R1, int L2, int R2, int temp[], int *cnt) {
int i = L1, j = L2, k = 0;
while (i <= R1 && j <= R2) {
(*cnt)++;
if (A[i] <= A[j]) {
temp[k++] = A[i++];
} else {
temp[k++] = A[j++];
}
}
while (i <= R1) {
temp[k++] = A[i++];
}
while (j <= R2) {
temp[k++] = A[j++];
}
for (int p = 0; p < k; p++) {
A[L1 + p] = temp[p];
}
}
void MergeSort(int A[], int left, int right, int temp[], int *cnt) {
if (left < right) {
int mid = (left + right) / 2;
MergeSort(A, left, mid, temp, cnt);
MergeSort(A, mid + 1, right, temp, cnt);
Merge(A, left, mid, mid + 1, right, temp, cnt);
}
}
int main() {
int A[MAXSIZE];
int n = MAXSIZE;
int temp[MAXSIZE];
int cnt = 0;
srand(time(NULL)); // 用系统时间初始化随机数生成器
for (int i = 0; i < n; i++) {
A[i] = rand() % 1000; // 生成0~999之间的随机整数
}
printf("原序列:\n");
for (int i = 0; i < n; i++) {
printf("%d ", A[i]);
}
// 直接插入排序
int cnt1 = InsertionSort(A, n);
printf("\n直接插入排序比较次数:%d\n", cnt1);
// 冒泡排序
for (int i = 0; i < n; i++) {
A[i] = rand() % 1000;
}
int cnt2 = BubbleSort(A, n);
printf("冒泡排序比较次数:%d\n", cnt2);
// 希尔排序
for (int i = 0; i < n; i++) {
A[i] = rand() % 1000;
}
int cnt3 = ShellSort(A, n);
printf("希尔排序比较次数:%d\n", cnt3);
// 快速排序
for (int i = 0; i < n; i++) {
A[i] = rand() % 1000;
}
QuickSort(A, 0, n - 1, &cnt);
printf("快速排序比较次数:%d\n", cnt);
// 归并排序
for (int i = 0; i < n; i++) {
A[i] = rand() % 1000;
}
int cnt5 = 0;
MergeSort(A, 0, n - 1, temp, &cnt5);
printf("归并排序比较次数:%d\n", cnt5);
return 0;
}
```
这里使用了随机数生成器生成随机整数序列,然后分别对序列进行直接插入、冒泡、希尔、快速、归并排序,并统计每种排序算法的比较次数。
阅读全文