
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
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
- Related Articles
- Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix using Python?
- Find median in row wise sorted matrix in C++
- JavaScript Program to Find median in row wise sorted matrix
- Find a common element in all rows of a given row-wise sorted matrix in C++
- Print all permutations in sorted (lexicographic) order in C++
- Sort the matrix row-wise and column-wise using Python
- Python program to print sorted number formed by merging all elements in array
- Print uncommon elements from two sorted arrays
- Program to find squared elements list in sorted order in Python
- Row-wise vs column-wise traversal of matrix in C++
- Python - Get items in sorted order from given dictionary
- Print Binary Tree levels in sorted order in C++
- How to search in a row wise and column wise increased matrix using C#?
- Program to print matrix elements in spiral order in python
- Count all sorted rows in a matrix in C++

Advertisements