Advertisement
Guest User

Untitled

a guest
May 22nd, 2015
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. #include <cstdio>
  2. #include <queue>
  3. using namespace std;
  4. int count(int[],int,int);
  5. int countSplitInversions(int[],int,int,int);
  6. int main() {
  7. int array[] = {1,3,5,2,4,6};
  8. int size = sizeof(array) / sizeof(array[0]);
  9. printf("%d\n",count(array,0,size-1));
  10. return 0;
  11. }
  12. int count(int array[],int low, int high) {
  13. int middle, x = 0, y = 0, z = 0;
  14. if(high == 0) return 0;
  15. else {
  16. if(low < high) {
  17. middle = ((low + high) / 2);
  18. x = count(array,low,middle);
  19. y = count(array,middle+1,high);
  20. z = countSplitInversions(array,low,middle,high);
  21. }
  22. }
  23. return x + y + z;
  24. }
  25. int countSplitInversions(int array[],int low, int middle, int high) {
  26. queue<int> q1;
  27. queue<int> q2;
  28. int contInversions = 0;
  29. for(int i=low;i<=middle;i++) q1.push(array[i]);
  30. for(int i=middle+1;i<=high;i++) q2.push(array[i]);
  31. int i = low;
  32. while(!(q1.empty() || q2.empty())) {
  33. if(q1.front() <= q2.front()) {
  34. array[i++] = q1.front();
  35. q1.pop();
  36. } else {
  37. array[i++] = q2.front();
  38. q2.pop();
  39. contInversions += q1.size();
  40. }
  41. }
  42. while(!q1.empty()) {
  43. array[i++] = q1.front();
  44. q1.pop();
  45. }
  46. while(!q2.empty()) {
  47. array[i++] = q2.front();
  48. q2.pop();
  49. contInversions += q1.size();
  50. }
  51. return contInversions;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement