You are viewing a single comment's thread. Return to all comments →
Pretty easy with modified merge sort.
def insertionSort(arr): arr, count = mergeCountInversions(arr) return count def mergeCountInversions(arr): if len(arr) < 2: return arr, 0 c = len(arr) // 2 left, lc = mergeCountInversions(arr[:c]) right, rc = mergeCountInversions(arr[c:]) merged = [0] * len(arr) count = lc + rc lpos = 0 rpos = 0 for i in range(len(arr)): if lpos == len(left): side = 'r' elif rpos == len(right): side = 'l' elif left[lpos] <= right[rpos]: side = 'l' else: side = 'r' if side == 'l': merged[i] = left[lpos] lpos += 1 else: merged[i] = right[rpos] rpos += 1 count += len(left) - lpos return merged, count
Seems like cookies are disabled on this browser, please enable them to open this website
Insertion Sort Advanced Analysis
You are viewing a single comment's thread. Return to all comments →
Pretty easy with modified merge sort.