剑指offer-数组中的逆序对

来源:互联网 发布:成都数据分析咨询公司 编辑:程序博客网 时间:2024/06/08 05:27

题目:

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。

归并排序的运用。

int InversePairs(int *data, int length){if (data == NULL || length < =0)return 0;int *copy = new int[length];for (int i = 0; i < length; i++)copy[i] = data[i];int count = InversePairsCore(data, copy, 0, length - 1);delete []copy;return count;}int InversePairsCore(int *data, int *copy, int start, int end){if (start == end){copy[start] = data[start];return 0;}int length = (end - start) / 2;int left = InversePairsCore(data, copy, start, start + length);int right = InversePairsCore(data, copy, start + length + 1, end);int i = start + length;int j = end;int count = 0;int indexCpy = end;while (i>start&&j>start+length+1){if (data[i]>data[j]){copy[indexCpy--] = data[i--];count++;}elsecopy[indexCpy--] = data[j--];}for (; i>=start; i--)copy[indexCpy--] = data[i];for (; j >= start + length + 1; j--)copy[indexCpy--] = data[j];return left + right + count;}


原创粉丝点击