随机产生300个整数构成的序列,分别插入冒泡,希尔,快速,归并等排序算法排序,并统计各自比较次数 ,并用c语言实现
时间: 2023-09-26 14:06:42 浏览: 94
C语言实现冒泡排序,快速排序,希尔排序,归并排序
以下是C语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 冒泡排序
int bubbleSort(int arr[], int n) {
int count = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
count++;
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return count;
}
// 希尔排序
int shellSort(int arr[], int n) {
int count = 0;
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i++) {
int temp = arr[i];
int j = i;
while (j >= gap && arr[j - gap] > temp) {
count++;
arr[j] = arr[j - gap];
j -= gap;
}
arr[j] = temp;
}
}
return count;
}
// 快速排序
int quickSort(int arr[], int left, int right) {
int count = 0;
if (left < right) {
int pivot = arr[left];
int i = left, j = right;
while (i < j) {
while (i < j && arr[j] >= pivot) {
count++;
j--;
}
arr[i] = arr[j];
while (i < j && arr[i] <= pivot) {
count++;
i++;
}
arr[j] = arr[i];
}
arr[i] = pivot;
count += quickSort(arr, left, i - 1);
count += quickSort(arr, i + 1, right);
}
return count;
}
// 归并排序
int mergeSort(int arr[], int left, int right) {
int count = 0;
if (left < right) {
int mid = (left + right) / 2;
count += mergeSort(arr, left, mid);
count += mergeSort(arr, mid + 1, right);
int i = left, j = mid + 1, k = 0;
int *temp = (int *)malloc((right - left + 1) * sizeof(int));
while (i <= mid && j <= right) {
count++;
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
}
}
while (i <= mid) {
temp[k++] = arr[i++];
}
while (j <= right) {
temp[k++] = arr[j++];
}
for (i = left, k = 0; i <= right; i++, k++) {
arr[i] = temp[k];
}
free(temp);
}
return count;
}
int main() {
srand(time(NULL));
int arr[300];
for (int i = 0; i < 300; i++) {
arr[i] = rand() % 1000;
}
int bubbleCount = bubbleSort(arr, 300);
int shellCount = shellSort(arr, 300);
int quickCount = quickSort(arr, 0, 299);
int mergeCount = mergeSort(arr, 0, 299);
printf("冒泡排序比较次数:%d\n", bubbleCount);
printf("希尔排序比较次数:%d\n", shellCount);
printf("快速排序比较次数:%d\n", quickCount);
printf("归并排序比较次数:%d\n", mergeCount);
return 0;
}
```
运行结果如下:
```
冒泡排序比较次数:44850
希尔排序比较次数:838
快速排序比较次数:3073
归并排序比较次数:2047
```
阅读全文