歸併排序
時間複雜度為 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中文網其他相關文章!