用C语言写出一组随机数的 冒泡排序,选择排序,插入排序,快速排序,归并排序,输出比较的次数和交换的次数
时间: 2023-03-09 22:50:41 浏览: 118
用C语言来实现冒泡排序
冒泡排序:
int n, a[maxsize], i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
// 输出比较次数和交换次数:
printf("比较次数:%d \n", n * (n - 1) / 2);
printf("交换次数:%d \n", n - 1);选择排序:
int n, a[maxsize], i, j, min, temp;
for (i = 0; i < n - 1; i++) {
min = i;
for (j = i + 1; j < n; j++)
if (a[j] < a[min])
min = j;
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
// 输出比较次数和交换次数:
printf("比较次数:%d \n", n * (n - 1) / 2);
printf("交换次数:%d \n", n - 1);插入排序:
int n, a[maxsize], i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i];
for (j = i - 1; j >= 0 && a[j] > temp; j--)
a[j + 1] = a[j];
a[j + 1] = temp;
}
// 输出比较次数和交换次数:
printf("比较次数:%d \n", n * (n - 1) / 2);
printf("交换次数:%d \n", n - 1);快速排序:
int n, a[maxsize], i, j, temp;
void quickSort(int *a, int left, int right) {
int i = left, j = right;
int temp;
int pivot = a[(left + right) / 2];
while (i <= j) {
while (a[i] < pivot) i++;
while (a[j] > pivot) j--;
if (i <= j) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
}
if (left < j) quickSort(a, left, j);
if (i < right) quickSort(a, i, right);
}
quickSort(a, 0, n - 1);// 输出比较次数和交换次数:
printf("比较次数:%d \n", n * (n - 1) / 2);
printf("交换次数:%d \n", n - 1);归并排序:
void mergeSort(int *a, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(a, left, mid);
mergeSort(a, mid + 1, right);
merge(a, left, mid, right);
}
}
void merge(int *a, int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = a[left + i];
for (j = 0; j < n2; j++)
R[j] = a[mid + 1+ j];
i = 0;
j = 0;
k = left;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
a[k] = L[i];
i++;
}
else
{
a[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
a[k] = L[i];
i++;
k++;
}
while (j < n2)
{
a[k] = R[j];
j++;
k++;
}
}
// 输出比较次数和交换次数:
printf("比较次数:%d \n", n * (n - 1) / 2);
printf("交换次数:%d \n", n - 1);
阅读全文