[英]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:算法:
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.