I have one sorted 2dimensional array (the rows are in ascending order). I want to transform it to one sorted 1dimensional array to use it in one of my functions. How can I do it?
Thanks for the help!
Assuming that the subarrays have the same length and that the first element of each row is no less than the last element of the previous row:
Object[][] twoDArray;
// you are initializing it with some code here
int len = 0;
for (Object[] x : twoDArray) {
len += x.length;
}
Object[] oneDArray = new Object[len];
for (int i=0; i<len; ++i) {
oneDArray[i] = twoDArray[i/twoDArray.length][i%twoDArray.length];
}
This has O(n + m)
complexity.
If my second assumption is faulty (as you seem to indicate in your comments), then you should call Arrays.sort
on your final array. The final complexity will be O(n + m + nlogn
).
It is almost certain that you cannot optimize your sorting more than this. Sorting in the middle of your array conversion will require another full iteration per sub-iteration, in order to insert the element from the next row in its proper location and then move each element ahead of it up one index.
Assuming your bidimensional array is R Rows and C columns. You can
In the end, you should have a monodimensional array with all elements already sorted without further operations.
The easiest way will be to:
You may be able to use the fact the arrays are already sorted to try and do something fancy with insertion but the performance gains will be small and the increase in code complexity will be massive. You are far more likely to add bugs than to gain performance.
To do the sorted insertion you would need an array of indexes for each source array.