Printing All Elements in Sorted Order from Row and Column Wise Sorted Matrix.Matrices are fundamental data structures used to represent two-dimensional arrays. When dealing with matrices that are sorted both row-wise and column-wise, we can efficiently print all elements in sorted order using various approaches. In this article, we'll explore different strategies to achieve this goal using the Java programming language. Approach 1: Flattening and Sorting The simplest approach is to flatten the matrix into a one-dimensional array and then sort that array. Here's how to do it: Flatten the Matrix: Traverse the matrix row by row and add all elements to a one-dimensional array. Sort the Array: After flattening the matrix, apply a sorting algorithm (e.g., quicksort or mergesort) to sort the array. Print the Sorted Array: Iterate through the sorted array and print the elements. This approach is straightforward, but it might not be the most efficient, especially for larger matrices. Output: In this code:
Time Complexity : O(n*m) + O((n+m)log(n+m)) n*m for traversing the 2D matrix ((n+m)log(n+m)) for sorting the array of size n+m Space complexity : O(n+m) Since we are using an additional space to store 2D matrix to 1D matrix Approach 2: Merge Sorted Arrays Since the matrix is sorted both row-wise and column-wise, we can treat each row as a sorted array and merge them to get a single sorted array. Create an Empty Min-Heap: Initialize a min-heap (priority queue) and insert the first element from each row along with the row and column indices. Extract Minimum and Insert Next: Repeatedly extract the minimum element from the heap, print it, and then insert the next element from the same row (if available). Continue this process until the heap is empty. Output: In this code:
This process continues until all elements have been printed, resulting in the matrix elements being printed in ascending order. Time Complexity: The time complexity of the "Merge Sorted Arrays" approach is primarily determined by the number of elements in the matrix (m) and the number of rows in the matrix (k): Merging Step: O(m) Priority Queue Operations: O(m * log k) Therefore, the overall time complexity is O(m * log k), where m is the total number of elements in the matrix, and k is the number of rows. Space Complexity: The space complexity is influenced by the space used to store the priority queue and other variables: Priority Queue: O(k) Other Variables: Constant space Thus, the overall space complexity is O(k), where k is the number of rows. Next TopicArraylist vs linked list |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India