+ 4
Which is the best method to sort a 2D array?
My teacher transferred the 2D array to a 1D array and applied bubble sort. I did it using a nested loop without transfer. Take a look at my code. Please suggest the most efficient method to complete the task. https://code.sololearn.com/clwzz3U74u4w/?ref=app
8 Answers
+ 1
well idk why your teacher did that as flattening an array already takes enough time, and then to apply an O(nÂČ) sorting algorithm would make the execution time horrible. what you did was pretty efficient but there could be a potentially (very slightly) faster solution. so you did pretty good.
+ 2
Flattening array is not slow, it takes only time proportional to the number of elements in the array.
The slow part is the bubble sort. If you want to do it efficiently, use fast sorting algorithm, for example QuickSort, MergeSort, HeapSort...
+ 2
hinanawi Although flattening is O(n*m), you nevertheless sort n*m elements, so it takes at least O(nm log(nm))
+ 1
thanks
+ 1
michal when talking best optimization, flattening an array is an n*m complexity operation, so for smaller matrices yes that can work but for larger ones it is a big time-waster, i'm just talking general scenarios here.
- 1
merge sort
- 3
insertion sort
- 5
buble sort