Original title:
Suppose the Subarray a[0] to a[n-1] are sorted and the Subarray A[n] to a[2*n-1) is sorted. How can i merge the subarrays so, a[0] to a[2*n-1] are sorted using an auxiliary array of length n (Inst EAD of 2n)
Analysis:
For two of the size of an ordered array of N to merge, requiring a spatial complexity of n, under normal circumstances, the spatial complexity of the merge order here is 2n, but because two sub-arrays are ordered, it is a reasonable requirement to use the extra subspace of size n to merge, and realize the following:
1 Importjava.util.Arrays;2 ImportEdu.princeton.cs.algs4.StdRandom;3 4 Public classMergesortedsubarray {5 Private Static BooleanLess (comparable V, comparable W) {6 returnV.compareto (W) < 0;7 }8 Public Static voidmerge (comparable[] array) {9 intn = array.length/2;Tencomparable[] aux =NewComparable[n]; One for(inti=0;i<n;i++) {//take the left half of the sorted element to the auxiliary array, because the left position of the future merge may be occupied by the right element AAux[i] =Array[i]; - } - System.out.println (arrays.tostring (aux)); the intL = 0; - intR =N; - for(intk = 0; k<2*n;k++){ - if(l >= N) Break;//The array of auxiliary elements is exhausted, and the right side of the array does not need to be shifted. + Else if(R>=2*n) array[k]=aux[l++];//all elements of the right element of array are placed in the appropriate position, then simply move the elements of the auxiliary array to the right of the array - Else if(Less (array[r],aux[l])) array[k] = array[r++]; + ElseArray[k] = aux[l++]; A } at } - - Public Static voidMain (string[] args) { - intn = 10; - int[] Subarray1 =New int[n]; - int[] Subarray2 =New int[n]; in for(inti = 0; I < n; i++) { -Subarray1[i] = stdrandom.uniform (100); toSubarray2[i] = stdrandom.uniform (100); + } - Arrays.sort (subarray1); the Arrays.sort (subarray2); *integer[] Array =Newinteger[2*n]; $ for(inti = 0; i<n;i++){Panax NotoginsengArray[i] =Subarray1[i]; -Array[n+i] =Subarray2[i]; the } + System.out.println (arrays.tostring (array)); A merge (array); the System.out.println (arrays.tostring (array)); + } -}
Coursera algorithms week3 Merge sort exercise quiz 1:merging with smaller auxiliary array