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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP