Algo:
i have followed to do the same
i have followed to do the same
- Merge sort array A and create a copy (array B)
- Take A[1] and find its position in sorted array B via a binary search. The number of inversions for this element will be one less than the index number of its position in B since every lower number that appears after the first element of A will be an inversion.2a. accumulate the number of inversions to counter variable num_inversions.2b. remove A[1] from array A and also from its corresponding position in array B
- rerun from step 2 until there are no more elements in A.
Here’s an example run of this algorithm. Original array A = ( 14, 8, 12, 3, 2)
1: Merge sort and copy to array B
B = (2,3,8,12,14)
2: Take A[1] and binary search to find it in array B
A[1] = 14
B = (2,3,8,12,14)
14 is in the 5th position of array B, thus there are 4 inversions. We know this because 14 was in the first position in array A, thus any lower value element that subsequently appears in array A would have an index of j > i (since i in this case is 1).
2.b: Remove A[1] from array A and also from its corresponding position in array B (bold elements are removed).
A = ( 14, 8, 12, 3, 2) = (8, 12, 3, 2)
B = (2,3,8,12,14) = ((2,3,8,12)
3: Rerun from step 2 on the new A and B arrays.
A[1] = 8
B = ((2,3,8,12)
8 is now in the 3rd position of array B, thus there are 2 inversions. We know this because 8 was in the first position in array A, thus any lower value element that subsequently appears would have an index of j > i (since i in this case is again 1). Remove A[1] from array A and also from its corresponding position in array B (bold elements are removed)
A = (8, 12, 3, 2) = 12,3,2
B = (2,3,8,12) = 2,3,12
Continuing in this vein will give us the total number of inversions for array A once the loop is complete
Try to code as per Algo , it gives a complete result
i am not sharing code as its against the fair code Stanford rule and will share only once the date for submitting assignment is expired
however am okay if u need any help in completing this exercise and Java is teh language i prefer to code in