随机产生300个整数构成的序列,分别以直接插入、冒泡、希尔、快速、归并等排序算法排序,并统计各自的比较次数。代码怎么写 用c语言写
时间: 2023-12-10 22:37:22 浏览: 44
以下是使用C语言实现各种排序算法的代码,包括直接插入排序、冒泡排序、希尔排序、快速排序和归并排序,并统计了它们的比较次数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* 直接插入排序 */
int direct_insertion_sort(int arr[], int n)
{
int i, j, k, count = 0;
for (i = 1; i < n; i++) {
k = arr[i];
for (j = i - 1; j >= 0 && arr[j] > k; j--) {
arr[j + 1] = arr[j];
count++;
}
arr[j + 1] = k;
}
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 - 1 - i; 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++) {
tmp = arr[i];
for (j = i - gap; j >= 0 && arr[j] > tmp; j -= gap) {
arr[j + gap] = arr[j];
count++;
}
arr[j + gap] = tmp;
}
}
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;
while (i < j) {
while (i < j && arr[j] >= pivot) {
j--;
count++;
}
if (i < j) {
arr[i] = arr[j];
i++;
count++;
}
while (i < j && arr[i] < pivot) {
i++;
count++;
}
if (i < j) {
arr[j] = arr[i];
j--;
count++;
}
}
arr[i] = pivot;
count += quick_sort(arr, left, i - 1);
count += quick_sort(arr, i + 1, right);
}
return count;
}
/* 归并排序 */
int merge(int arr[], int left, int mid, int right)
{
int i, j, k, count = 0;
int *tmp = (int*)malloc((right - left + 1) * sizeof(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++];
count++;
}
while (j <= right) {
tmp[k++] = arr[j++];
count++;
}
for (i = left, k = 0; i <= right; i++, k++) {
arr[i] = tmp[k];
}
free(tmp);
return count;
}
int merge_sort(int arr[], int left, int right)
{
int mid, count = 0;
if (left < right) {
mid = (left + right) / 2;
count += merge_sort(arr, left, mid);
count += merge_sort(arr, mid + 1, right);
count += merge(arr, left, mid, right);
}
return count;
}
int main()
{
int arr[300], i;
int direct_insertion_count, bubble_count, shell_count, quick_count, merge_count;
/* 生成随机数序列 */
srand(time(NULL));
for (i = 0; i < 300; i++) {
arr[i] = rand();
}
/* 直接插入排序 */
direct_insertion_count = direct_insertion_sort(arr, 300);
printf("直接插入排序比较次数:%d\n", direct_insertion_count);
/* 冒泡排序 */
bubble_count = bubble_sort(arr, 300);
printf("冒泡排序比较次数:%d\n", bubble_count);
/* 希尔排序 */
shell_count = shell_sort(arr, 300);
printf("希尔排序比较次数:%d\n", shell_count);
/* 快速排序 */
quick_count = quick_sort(arr, 0, 299);
printf("快速排序比较次数:%d\n", quick_count);
/* 归并排序 */
merge_count = merge_sort(arr, 0, 299);
printf("归并排序比较次数:%d\n", merge_count);
return 0;
}
```
阅读全文