
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
Counting Inversions Using Set in C++ STL
In this tutorial, we will be discussing a program to count inversions using set in C++ STL.
Inversion count is a measure of how near the array is to be completely sorted. If the array is already sorted, the inversion count will be 0.
Example
#include<bits/stdc++.h> using namespace std; //returning inversion count int get_Icount(int arr[],int n){ multiset<int> set1; set1.insert(arr[0]); int invcount = 0; //initializing result multiset<int>::iterator itset1; for (int i=1; i<n; i++){ set1.insert(arr[i]); itset1 = set1.upper_bound(arr[i]); invcount += distance(itset1, set1.end()); } return invcount; } int main() { int arr[] = {8, 4, 2, 1}; int n = sizeof(arr)/sizeof(int); cout << "Number of inversions count are : "<< get_Icount(arr,n); return 0; }
Output
Number of inversions count are : 6
Advertisements