C ++程序计算数组中的反转
计数反转是指对数组进行排序所需的开关数量。数组排序时,反转计数=0。当数组以相反顺序排序时,反转计数=最大值。
让我们开发一个C++程序来计算数组中的反转。
算法
Begin
Function CountInversionArray has arguments a[], n = number of elements.
initialize counter c := 0
for i in range 0 to n-1, do
for j in range (i + 1) to n, do
if a[i] > a[j], then
increase the count by 1
done
done
End.范例程式码
#include<iostream>
using namespace std;
int CountInversionArray(int a[], int n) {
int i, j, c = 0;
for(i = 0; i < n; i++) {
for(j = i+1; j < n; j++)
if(a[i] > a[j])
c++;
}
return c;
}
int main() {
int n, i;
cout<<"\nEnter the number of elements: ";
cin>>n;
int a[n];
for(i = 0; i < n; i++) {
cout<<"Enter element "<<i+1<<": ";
cin>>a[i];
}
cout<<"\nThe number of inversion in the array: "<<CountInversionArray(a, n);
return 0;
}输出结果
Enter the number of elements: 5 Enter element 1: 3 Enter element 2: 2 Enter element 3: 7 Enter element 4: 6 Enter element 5: 1 The number of inversion in the array: 6
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短