问题描述
这是一种计算数组倒数的算法,一种分治算法。我想知道这个算法的基本操作是什么,如何建立递归关系来分析基本步骤的执行次数?
基本步骤的定义:对算法总运行时间贡献最大的操作。它通常是算法最内层循环中最耗时的操作。
示例:按键比较操作;算术运算(除法最耗时,乘法次之)。
这是算法
public static int merge(int[] arr,int[] aux,int low,int mid,int high)
{
int k = low,i = low,j = mid + 1;
int inversionCount = 0;
// while there are elements in the left and right runs
while (i <= mid && j <= high)
{
if (arr[i] <= arr[j]) {
aux[k++] = arr[i++];
}
else {
aux[k++] = arr[j++];
inversionCount += (mid - i + 1); // NOTE
}
}
// copy remaining elements
while (i <= mid) {
aux[k++] = arr[i++];
}
// no need to copy the second half
// copy back to the original array to reflect sorted order
for (i = low; i <= high; i++) {
arr[i] = aux[i];
}
return inversionCount;
}
// Sort array `arr[low…high]` using auxiliary array `aux`
public static int mergeSort(int[] arr,int high)
{
// Base case
if (high == low) { // if run size == 1
return 0;
}
// find midpoint
int mid = (low + ((high - low) >> 1));
int inversionCount = 0;
// recursively split runs into two halves until run size == 1,// then merges them and return up the call chain
// split/merge left half
inversionCount += mergeSort(arr,aux,low,mid);
// split/merge right half
inversionCount += mergeSort(arr,mid + 1,high);
// merge the two half runs
inversionCount += merge(arr,mid,high);
return inversionCount;
}
如何设置递归关系来分析基本步骤的执行次数?还请提供解释。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)