To print all elements in sorted order from row and column wise sorted matrix in Python



Sometimes we need all the elements of a matrix in a sorted order. But as a matrix is in form of rows and columns, we do not apply the usual sorting algorithms to get the result. Rather we use the below user defined functions to get the elements sorted.

Example

 Live Demo

def heapq(a, k, i):
   greater = i
   l = 2 * i + 1
   r = 2 * i + 2
   if l < k and a[i] < a[l]:
      greater = l
   if r < k and a[greater] < a[r]:
      greater = r
   if greater != i:
      a[i], a[greater] = a[greater], a[i]
      heapq(a, k, greater)

def Sort(val):
   n = len(val)
   for i in range(n, -1, -1):
      heapq(val, n, i)
   for i in range(n - 1, 0, -1):
      val[i], val[0] = val[0], val[i]
      heapq(val, i, 0)
x = [11, 3, 50, 75, 4, 32, 9, 2, 15]
Sort(x)
n = len(x)
print("Sorted values are")
for i in range(n):
   print("%d" % x[i])

Running the above code gives us the following result −

Output

Sorted values are
2
3
4
9
11
15
32
50
75

Advertisements