归并排序
时间复杂度为 O(nlogn) 的排序算法之一,其中 n 是给定数组的长度。
///tc : O(nlogn) //sc : O(n) for creating intermediate arrays a, b of size of part of subarray which is of size n class Solution { public int[] sortArray(int[] nums) { merge(0,nums.length-1,nums); return nums; } public void merge(int start, int end, int arr[]){ if(end>start){ int mid = (start+end)/2; merge(start,mid,arr); merge(mid+1,end,arr); sort(start, mid,end, arr); } } public void sort(int start, int mid ,int end, int arr[]){ int a[] = new int[mid-start+1]; int b[] = new int[end-mid]; for(int i = 0;i <hr> <p>反转计数</p> <p>在数组排序之前需要进行多少次比较(给定数组 arr[] 的索引 i, j ,<strong>arr[i]> arr[j]</strong> (对于 j> i)将递增每次满足此条件,反转计数加 1。</p> <p>注意:<em>我们可以使用相同的合并排序方法来查找反转计数(合并排序代码已稍微更改以使其更具可读性)</em><br> </p> <pre class="brush:php;toolbar:false">class Solution { // arr[]: Input Array // N : Size of the Array arr[] // Function to count inversions in the array. static long inversionCount(long arr[], int n) { // Your Code Here //we can use merge sort long temp[]= new long[n]; return merge(0,n-1,arr,temp); } public static long merge(int start, int end, long arr[],long[] temp){ long count = 0; if(end>start){ int mid = (start+end)/2; count+=merge(start,mid,arr,temp); count+=merge(mid+1,end,arr,temp); count+=sort(start, mid,end, arr,temp); } return count; } public static long sort(int start, int mid ,int end, long arr[],long [] temp){ long count = 0; int i = start; int j = mid+1; int k = start; while(i arr[j] then all the values after ith index including will be // greater that jth index value hence count += mid-i+1 } k++; } while(i
以上是数组的详细内容。更多信息请关注PHP中文网其他相关文章!