用c语言实现,随机产生300 个整数构成的序列,分别以直接插入、希尔、快速、归并等排序算法排序,并统计各自的比较...
时间: 2023-12-06 13:45:08 浏览: 71
用C实现了排序算法中的插入排序、选择排序、冒泡排序、希尔排序、归并排序、快速排序、桶排序、基数排序
以下是用C语言实现的代码,其中包含直接插入排序、希尔排序、快速排序和归并排序算法,以及对比较次数的统计。
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXSIZE 300
void insertSort(int arr[], int n, int *compCount) {
int i, j, temp;
for (i = 1; i < n; i++) {
temp = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > temp) {
(*compCount)++;
arr[j + 1] = arr[j];
j--;
}
(*compCount)++;
arr[j + 1] = temp;
}
}
void shellSort(int arr[], int n, int *compCount) {
int i, j, gap, temp;
for (gap = n / 2; gap > 0; gap /= 2) {
for (i = gap; i < n; i++) {
temp = arr[i];
for (j = i - gap; j >= 0 && arr[j] > temp; j -= gap) {
(*compCount)++;
arr[j + gap] = arr[j];
}
(*compCount)++;
arr[j + gap] = temp;
}
}
}
int partition(int arr[], int low, int high, int *compCount) {
int pivot = arr[low];
while (low < high) {
while (low < high && arr[high] >= pivot) {
(*compCount)++;
high--;
}
arr[low] = arr[high];
while (low < high && arr[low] <= pivot) {
(*compCount)++;
low++;
}
arr[high] = arr[low];
}
arr[low] = pivot;
return low;
}
void quickSort(int arr[], int low, int high, int *compCount) {
if (low < high) {
int pivotPos = partition(arr, low, high, compCount);
quickSort(arr, low, pivotPos - 1, compCount);
quickSort(arr, pivotPos + 1, high, compCount);
}
}
void merge(int arr[], int l, int mid, int r, int *compCount) {
int i, j, k;
int n1 = mid - l + 1;
int n2 = r - mid;
int L[n1], R[n2];
for (i = 0; i < n1; i++) {
L[i] = arr[l + i];
}
for (j = 0; j < n2; j++) {
R[j] = arr[mid + 1 + j];
}
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
(*compCount)++;
arr[k] = L[i];
i++;
} else {
(*compCount)++;
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r, int *compCount) {
if (l < r) {
int mid = l + (r - l) / 2;
mergeSort(arr, l, mid, compCount);
mergeSort(arr, mid + 1, r, compCount);
merge(arr, l, mid, r, compCount);
}
}
int main() {
int arr[MAXSIZE];
int i, j, temp;
int compCount;
srand((unsigned int) time(NULL));
for (i = 0; i < MAXSIZE; i++) {
arr[i] = rand();
}
// 直接插入排序
compCount = 0;
insertSort(arr, MAXSIZE, &compCount);
printf("直接插入排序比较次数: %d\n", compCount);
// 希尔排序
compCount = 0;
shellSort(arr, MAXSIZE, &compCount);
printf("希尔排序比较次数: %d\n", compCount);
// 快速排序
compCount = 0;
quickSort(arr, 0, MAXSIZE - 1, &compCount);
printf("快速排序比较次数: %d\n", compCount);
// 归并排序
compCount = 0;
mergeSort(arr, 0, MAXSIZE - 1, &compCount);
printf("归并排序比较次数: %d\n", compCount);
return 0;
}
```
该程序使用了四种不同的排序算法,并通过统计比较次数来比较它们的性能。对于给定的300个随机整数,程序输出每种排序算法的比较次数。
阅读全文