+ 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

31st Jul 2018, 10:05 AM
Zakaria Arzoo
Zakaria Arzoo - avatar
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.
31st Jul 2018, 11:45 AM
hinanawi
hinanawi - avatar
+ 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...
1st Aug 2018, 12:18 PM
michal
+ 2
hinanawi Although flattening is O(n*m), you nevertheless sort n*m elements, so it takes at least O(nm log(nm))
1st Aug 2018, 12:22 PM
michal
+ 1
thanks
31st Jul 2018, 11:46 AM
Zakaria Arzoo
Zakaria Arzoo - avatar
+ 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.
1st Aug 2018, 12:20 PM
hinanawi
hinanawi - avatar
- 1
merge sort
31st Jul 2018, 12:40 PM
Driss Aharik
Driss Aharik - avatar
- 3
insertion sort
31st Jul 2018, 12:40 PM
Driss Aharik
Driss Aharik - avatar
- 5
buble sort
31st Jul 2018, 12:39 PM
Driss Aharik
Driss Aharik - avatar