用c语言代码输出n个数的逆序数
时间: 2024-01-27 10:05:54 浏览: 94
输入n数逆序输出.cpp
以下是一个基于归并排序的算法,可以输出n个数的逆序数:
```
#include <stdio.h>
int merge(int arr[], int temp[], int left, int mid, int right) {
int i = left, j = mid, k = left;
int count = 0;
while (i <= mid - 1 && j <= right) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
count += mid - i;
}
}
while (i <= mid - 1) {
temp[k++] = arr[i++];
}
while (j <= right) {
temp[k++] = arr[j++];
}
for (i = left; i <= right; i++) {
arr[i] = temp[i];
}
return count;
}
int merge_sort(int arr[], int temp[], int left, int right) {
int mid, count = 0;
if (right > left) {
mid = (right + left) / 2;
count += merge_sort(arr, temp, left, mid);
count += merge_sort(arr, temp, mid + 1, right);
count += merge(arr, temp, left, mid + 1, right);
}
return count;
}
int main() {
int n, arr[100], temp[100], i;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the elements: ");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int count = merge_sort(arr, temp, 0, n - 1);
printf("Number of inversions: %d", count);
return 0;
}
```
在这个程序中,merge函数用于将两个已排序的子数组合并成一个已排序的数组,并计算逆序数的数量。merge_sort函数使用归并排序算法将数组分成两半,对各半部分递归调用merge_sort函数,并使用merge函数将这两个已排序的半部分合并成一个已排序的数组。最终,merge_sort函数返回逆序数的数量。程序接受用户输入的n个数,并输出逆序数的数量。
阅读全文