c语言编写两个程序分别用来求逆序数和判定序数
时间: 2023-07-15 08:10:58 浏览: 96
1. 求逆序数的程序:
```c
#include <stdio.h>
int merge(int arr[], int temp[], int left, int mid, int right) {
int i, j, k;
int count = 0;
i = left;
j = mid;
k = left;
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 mergeSort(int arr[], int temp[], int left, int right) {
int mid, count = 0;
if (right > left) {
mid = (right + left) / 2;
count = mergeSort(arr, temp, left, mid);
count += mergeSort(arr, temp, mid + 1, right);
count += merge(arr, temp, left, mid + 1, right);
}
return count;
}
int getInvCount(int arr[], int n) {
int temp[n];
return mergeSort(arr, temp, 0, n - 1);
}
int main() {
int arr[] = {1, 20, 6, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("逆序数为 %d", getInvCount(arr, n));
return 0;
}
```
2. 判断序列是否有序的程序:
```c
#include <stdio.h>
int isSorted(int arr[], int n) {
int i;
for (i = 1; i < n; i++) {
if (arr[i] < arr[i - 1]) {
return 0;
}
}
return 1;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
if (isSorted(arr, n)) {
printf("该序列有序\n");
} else {
printf("该序列无序\n");
}
return 0;
}
```
阅读全文