
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Inversion in an Array Using C++
Count inversion means the number of switches required to make an array sorted. Inversion count = 0, when array is sorted. Inversion count = maximum, when the array sorted in reverse order.
Let us develop a C++ program to count Inversion in an Array.
Algorithm
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.
Example Code
#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; }
Output
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
Advertisements