编程练习-求出数组逆序对
思路:
刚开始使用一个个遍历所有数对然后比较算出,时间复杂度为O(n^2);后来思考后发现可以基于归并排序来实现优化,归并排序可以在选出较大数字的过程,记录后半部分中小于前半部分某个数字的个数…
代码如下:
public class Main {
private static int res = 0;//逆序对个数
public static void main(String[] args) {
//归并排序
int[] array = {364,637,341,406,747,995,234,971,571,219,993,407,416,366,315,301,601,650,418,355,460,505,360,965,516,648,727,667,465,849,455,181,486,149,588,233,144,174,557,67,746,550,474,162,268,142,463,221,882,576,604,739,288,569,256,936,275,401,497,82,935,983,583,523,697,478,147,795,380,973,958,115,773,870,259,655,446,863,735,784,3,671,433,630,425,930,64,266,235,187,284,665,874,80,45,848,38,811,267,575};
int[] temp = new int[array.length];
for(int i=0;i<array.length;++i){
temp[i] = array[i];
}
mergeSort(array,temp,0,array.length-1);
for(int n:array) {
System.out.print(n+" ");
}
System.out.println(res);
}
private static void mergeSort(int[] array, int[] temp, int s, int e) {
if(s>=e) {
temp[s] = array[s];
return;
}
int m = (s+e)/2;
mergeSort(array,temp,s,m);
mergeSort(array,temp,m+1,e);
int c = e;
int i = m;
int j = e;
while(i>=s&&j>=m+1){
if(temp[i]>temp[j]){
array[c] = temp[i];
i--;
res += j-m;
}else{
array[c] = temp[j];
j--;
}
c--;
}
while(i>=s){
array[c] = temp[i];
i--;
c--;
}
while(j>=m+1){
array[c] = temp[j];
j--;
c--;
}
for(int z=s;z<=e;z++){
temp[z] = array[z];
}
}
}