简体   繁体   English

计算按升序排列然后降序排列的数组中的反转次数

[英]Count the number of inversions in an array that is sorted in increasing order then decreasing order

Given an array that is sorted in increasing order then decreasing order eg: {1, 3, 5, 4, 2}, I want to find the number of inversions required to sort this array in O(n).给定一个按递增顺序然后递减顺序排序的数组,例如:{1, 3, 5, 4, 2},我想找到在 O(n) 中对这个数组进行排序所需的反转次数。 This is my code which sorts such arrays in O(n):这是我的代码,它在 O(n) 中对这样的 arrays 进行排序:

void sort(long* a, long* result, long n)
 {
      long* start = &a[0];
      long* end = &a[n - 1];
      long count = 0;
      while (start <= end) {
        if (*start < *end) {
            result[count] = *start;
            start += 1;
        }
        else {
           result[count] = *end;
           end -= 1;
       }
      }
  }

In my code, I used 2 pointers from the start and end and stored the sorted array into the result array.在我的代码中,我从开始和结束使用了 2 个指针,并将排序后的数组存储到结果数组中。 How do I count the number of inversions using a similar algorithm?如何使用类似算法计算反转次数?

You could use this algorithm from "https://www.geeksforgeeks.org/counting-inversions/":您可以使用“https://www.geeksforgeeks.org/counting-inversions/”中的算法:
Algorithm:算法:

  1. Traverse through the array from start to end.从头到尾遍历数组。
  2. For every element find the count of elements smaller than the current number upto that index using another loop.对于每个元素,使用另一个循环找到小于该索引的当前数量的元素计数。
  3. Sum up the count of inversion for every index.总结每个索引的反转计数。
  4. Print the count of inversions.打印反转计数。

    You can also find a code example on their website.您还可以在他们的网站上找到代码示例。

Moreover, for your function it seems that you JUST need a new variable to store the number of oinversions you do.此外,对于您的 function ,您似乎只需要一个新变量来存储您执行的反转次数。

Hope it helped!希望它有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM