![](/img/trans.png)
[英]How do I count the number of swaps (inversions) and comparisons in my merge sort code for my Linked List?
[英]How to count number of inversions for large number of inputs using merge sort
我能夠計算少量輸入的反轉。 我應該進行哪些更改來計算 100000 個輸入的反轉次數。
#include<iostream>
using namespace std;
int _mergeSort(int arr[], int temp[], int left, int right);
int merge(int arr[], int temp[], int left, int mid, int right);
int mergeSort(int arr[], int array_size)
{
int temp[array_size];
return _mergeSort(arr, temp, 0, array_size - 1);
}
int _mergeSort(int arr[], int temp[], int left, int right)
{
int mid, inv_count = 0;
if (right > left)
{
/*Divide the array into two parts
and call _mergeSortAndCountInv()
for each of the parts*/
mid = (left + right) / 2;
/*Inversion count will be sum of inversions in left-part
right-part as well as number of inversions while merging */
inv_count = _mergeSort(arr, temp, left, mid); // counting inversions in the left part
inv_count += _mergeSort(arr, temp, mid + 1, right); //counting inversions in the right part
inv_count += merge(arr, temp, left, mid + 1, right);
}
return inv_count;
}
int merge(int arr[], int temp[], int left, int mid, int right)
{
int i, j, k;
int inv_count = 0;
i = left; // i is the index for left subarray
j = mid; // j is the index for right subarray
k = right; // k is the index for resultant merged subarray
while (i <= (mid - 1) && j <= right)
{
if (arr[i] < arr[j])
temp[k++] = arr[i++];
else
{
temp[k++] = arr[j++];
inv_count = inv_count + (mid - i);
}
}
// copying the remaining parts of the left subarray to temp (if any)
while (i <= (mid - 1))
temp[k++] = arr[i++];
// copying the remaining parts of the left subarray to temp (if any)
while (j <= right)
temp[k++] = arr[j++];
// copying back the merged elements to oroginal array ;
for (i = left; i <= right; i++)
{
arr[i] = temp[i];
}
return inv_count;
}
int main()
{
int arr[] = { 5, 7, 2, 3, 9, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
int ans = mergeSort(arr, n);
cout << "Number of inversions are" << "\n" << ans;
return 0;
}
k = 對; // k 是結果合並子數組的索引
這行有問題我猜應該是
k=左;
所以問題出在排序算法上。
合並排序的時間復雜度是Nlog(N)而你添加的只是一行
inv_count = inv_count + (mid - i);
恆定復雜性因此它不會改變算法的整體復雜性。 即使輸入是100000 ,計算數組中的反轉次數也不會有任何問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.