# 剑指offer解题报告(Java版)——求逆序对 36

ap1指向的7大于p2指向的6，所以这里就有p2的长度个逆序对

static void mergeSort(int[] data, int[] temp, int start, int end) {

if (start < end) {

int mid = (start + end) / 2;

mergeSort(data, temp, start, mid);

mergeSort(data, temp, mid + 1, end);

mergeArray(data, temp, start, mid, end);

}

}

private static void mergeArray(int[] data, int[] temp, int start, int mid,

int end) {

// TODO Auto-generated method stub

int leftPoint = start;

int leftEnd = mid;

int rightPoint = mid + 1;

int rightEnd = end;

int k = 0;

while (leftPoint <= leftEnd && rightPoint <= rightEnd) {

if (data[leftPoint] <= data[rightPoint]) {

temp[k++] = data[leftPoint++];

} else {

temp[k++] = data[rightPoint++];

}

}

while (leftPoint <= leftEnd) {

temp[k++] = data[leftPoint++];

}

while (rightPoint <= rightEnd) {

temp[k++] = data[rightPoint++];

}

}

private static int mergeArray(int[] data, int[] temp, int start, int mid,

int end) {

// TODO Auto-generated method stub

int leftPoint = mid;

int leftEnd = start;

int rightPoint = end;

int rightEnd = mid+1;

int k = end;

int count=0;

while (leftPoint >= leftEnd && rightPoint >= rightEnd) {

if (data[leftPoint] > data[rightPoint]) {

temp[k–] = data[leftPoint–];

count+=rightPoint-mid;

} else {

temp[k–] = data[rightPoint–];

}

}

while (leftPoint >= leftEnd) {

temp[k–] = data[leftPoint–];

}

while (rightPoint >= rightEnd) {

temp[k–] = data[rightPoint–];

}

return count;

}

static int mergeSort(int[] data, int[] temp, int start, int end) {

int left=0;

int right=0;

int mergeCount=0;

if (start < end) {

int mid = (start + end) / 2;

left=mergeSort(data, temp, start, mid);

right=mergeSort(data, temp, mid + 1, end);

mergeCount=mergeArray(data, temp, start, mid, end);

}

return left+right+mergeCount;

}

public static void main(String[] args) {

int[] data = { 1, 3, 5, 2, 4, 6 };

int[] temp = data.clone();

System.out.println(mergeSort(data, temp, 0, data.length – 1));

for (int k : temp)

System.out.println(k);

}

static int inversePairsATCG(String string) {

int count = 0;

char[] chars = string.toCharArray();

int[] left = new int[4];

for (int i = chars.length-1; i >=0; i–) {

char a = chars[i];

System.out.println(a);

switch (a) {

case ‘A’:

left[1]++;

left[2]++;

left[3]++;

break;

case ‘C’:

left[2]++;

left[3]++;

count += left[1];

break;

case ‘G’:

left[3]++;

count += left[2];

break;

case ‘T’:

count += left[3];

break;

default:

break;

}

}

return count;

}

public class InversePairsATCG {

public static void main(String[] args) {

String string=”ATAGC”;

System.out.println(inversePairsATCG(string));

}

}

原文作者：keedor
原文地址: https://www.cnblogs.com/keedor/p/4468940.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。