Advertisement
makispaiktis

DCP44 - Out of order arrays

Oct 13th, 2020 (edited)
2,310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. '''
  2. This problem was asked by Google.
  3. We can determine how "out of order" an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j.
  4. That is, a smaller element appears after a larger element.
  5. Given an array, count the number of inversions it has. Do this faster than O(N^2) time.
  6. You may assume each element in the array is distinct.
  7. For example, a sorted list has zero inversions. The array [2, 4, 1, 3, 5] has three inversions: (2, 1), (4, 2), and (4, 3).
  8. The array [5, 4, 3, 2, 1] has ten inversions: every distinct pair forms an inversion.
  9. '''
  10.  
  11. def countInversions(ARRAY):
  12.     # I will use bubblesort method
  13.     array = ARRAY.copy()
  14.     counter = 0
  15.     inversions = list()
  16.     for i in range(len(array)-1):
  17.         for j in  range(i+1, len(array)):
  18.             if array[i] > array[j]:
  19.                 array[i], array[j] = array[j], array[i]
  20.                 counter += 1
  21.                 inversions.append(str(array[i]) + "-" + str(array[j]))
  22.     return counter, inversions
  23.  
  24. # MAIN FUNCTION
  25. array1 = [2, 4, 1, 3, 5]
  26. counter1, inversions1 = countInversions(array1)
  27. print(str(array1) + " ----> " + str(counter1) + " inversions #### " + str(inversions1))
  28. array2 = [5, 4, 3, 2, 1]
  29. counter2, inversions2 = countInversions(array2)
  30. print(str(array2) + " ----> " + str(counter2) + " inversions #### " + str(inversions2))
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement