对随机产生的1000个整数构成的序列分别进行直接插入、简单选择排序、希尔、快速、归并排序,并统计各自的比较次数c语言代码
时间: 2023-08-13 22:04:33 浏览: 149
编程实现希尔、快速、堆、归并排序算法,随机产生10000个随机数存入磁盘文件,读取,并将不同排序方法的结果存入文件中(含报告)
5星 · 资源好评率100%
以下是对随机产生的1000个整数构成的序列分别进行直接插入、简单选择排序、希尔、快速、归并排序的C语言代码,并统计各自的比较次数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 直接插入排序
int directInsertionSort(int arr[], int n) {
int cmpCnt = 0;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
cmpCnt++;
}
arr[j + 1] = key;
}
return cmpCnt;
}
// 简单选择排序
int simpleSelectionSort(int arr[], int n) {
int cmpCnt = 0;
for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++) {
if (arr[minIdx] > arr[j]) {
minIdx = j;
}
cmpCnt++;
}
if (minIdx != i) {
int temp = arr[i];
arr[i] = arr[minIdx];
arr[minIdx] = temp;
}
}
return cmpCnt;
}
// 希尔排序
int shellSort(int arr[], int n) {
int cmpCnt = 0;
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i++) {
int temp = arr[i];
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
arr[j] = arr[j - gap];
cmpCnt++;
}
arr[j] = temp;
}
}
return cmpCnt;
}
// 快速排序
int quickSort(int arr[], int left, int right) {
int cmpCnt = 0;
if (left < right) {
int pivot = arr[left];
int i = left, j = right;
while (i < j) {
while (i < j && arr[j] >= pivot) {
j--;
cmpCnt++;
}
if (i < j) {
arr[i++] = arr[j];
cmpCnt++;
}
while (i < j && arr[i] < pivot) {
i++;
cmpCnt++;
}
if (i < j) {
arr[j--] = arr[i];
cmpCnt++;
}
}
arr[i] = pivot;
cmpCnt += quickSort(arr, left, i - 1);
cmpCnt += quickSort(arr, i + 1, right);
}
return cmpCnt;
}
// 归并排序
int merge(int arr[], int left, int mid, int right) {
int cmpCnt = 0;
int n1 = mid - left + 1;
int n2 = right - mid;
int L[n1], R[n2];
for (int i = 0; i < n1; i++) {
L[i] = arr[left + i];
}
for (int j = 0; j < n2; j++) {
R[j] = arr[mid + 1 + j];
}
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
cmpCnt++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
cmpCnt++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
cmpCnt++;
}
return cmpCnt;
}
int mergeSort(int arr[], int left, int right) {
int cmpCnt = 0;
if (left < right) {
int mid = (left + right) / 2;
cmpCnt += mergeSort(arr, left, mid);
cmpCnt += mergeSort(arr, mid + 1, right);
cmpCnt += merge(arr, left, mid, right);
}
return cmpCnt;
}
int main() {
int arr[1000];
srand(time(NULL));
for (int i = 0; i < 1000; i++) {
arr[i] = rand() % 1000;
}
int cmpCnt;
cmpCnt = directInsertionSort(arr, 1000);
printf("直接插入排序比较次数:%d\n", cmpCnt);
cmpCnt = simpleSelectionSort(arr, 1000);
printf("简单选择排序比较次数:%d\n", cmpCnt);
cmpCnt = shellSort(arr, 1000);
printf("希尔排序比较次数:%d\n", cmpCnt);
cmpCnt = quickSort(arr, 0, 999);
printf("快速排序比较次数:%d\n", cmpCnt);
cmpCnt = mergeSort(arr, 0, 999);
printf("归并排序比较次数:%d\n", cmpCnt);
return 0;
}
```
阅读全文