Java Arrays.sort(test) sorts two arrays - java

I have initiated an array in Java to be the same as another array. I have done this because I only want to sort a copy of the array not the original. This works fine the new array is filled with the original values. The problem then arises when I sort the array. The original also gets sorted. So my original is also sorted. How do I correct this so that only the copy of the array gets sorted.
double[] distancesSort = distances;
Arrays.sort(distancesSort);

= is not used to copy elements of one array into another.
Use
double[] distancesSort = Arrays.copyOf(distances,distances.length);
Arrays.copyOf(double[] arr, int length)
Copies the specified array, truncating or padding with zeros (if
necessary) so the copy has the specified length. For all indices that
are valid in both the original array and the copy, the two arrays will
contain identical values. For any indices that are valid in the copy
but not the original, the copy will contain 0L. Such indices will
exist if and only if the specified length is greater than that of the
original array.
Parameters:
arr - the array to be copied
length - the length of the copy to be
returned
Returns:
a copy of the original array, truncated or padded with zeros to obtain
the specified length
If you use = then distancesSort will refer to distances. Any changes in distancesSort will reflect the changes in distances also.

Related

Length of list pattern

I have a list where I am trying to find the sum of combination of the lists entries, except the entries where both values to add are equal to each other (ie 2+2 would not be added) and add them to another list.
As an example:
[1,2,3] would yield the list of sums [3,4,5] because 1+2=5,1+3=4, and 2+3=5
However, my issues arises with not knowing how many sums will be produced. I am working in java and am limited to native arrays, therefore the size of the array has to be set before I can add the sum values to it.
I know I would not be able to find the exact size of the sum list due to the possibility that a sum would not get added if the two elements are the same, but I am trying to ballpark it so I don't have massive arrays.
The closest 'formula' I have gotten is setting the following, but it is never precisely what the max value would be for any list
(list length of original numbers * list length of original numbers) / 2
I am trying to keep time complexity in mind, so keeping a running count of how many sums there are, setting an array to that size, and looping through the original list again would not be efficient.
Any suggestions?
Can you add same sums to array, I mean, your array is {1,2,3,4,5}. Would you print the both result of 1+5 and 2+4 =6.
If your answer is yes. You can get the length of array and multiply it with 1 less and divide them to 2. For instance; our array → {1,2,3,4,5} the lenght is 5 the length of our result array will be 5*4/2=10.
Or you can use lists in java if you cant define a length for array. Keep in mind.

Why does the multidimensional array syntax work

When we create a 2d array such as int[][] a = new int[2][3] why is the resulting 2d array consist of a two-element array that contains three-element int arrays instead of the other way around. The reason why I'm confused is that when we make an array we do datatype[], so when we do int[2][3] why don't we put three int[2] arrays into an array with three spots (from the [3]).
The way it's implemented in Java is more logical. Consider the array element access expression: a[x][y]. Currently, it could be nicely decomposed to (a[x])[y] which means "we get an x-th element of a, then we get a y-th element of the result". So imagine if new int[2][3] produced an array of three elements, each is a two-element array. Then the x should be in range 0..2 and y should be in range 0..1 which is the opposite of the dimension order used at the array creation point. That would be absolutely confusing.
I guess you have a point with your logic. Eventhough you could also argument, writing int[2][3] means "first index can have 2 different values, second 3", what leads to the same as how it really works.
In the end, this is just a matter of specification and compilerbuilding. And since it is specified this way and not that way, it is implemented and works this way.

Increasing Array Index without using Arraylist or Copying Elements over to another Array

I have an assignment for class that requires increasing the size of an arrays index.
The instruction mentions not to create a new array and copying the elements, calling it rather inefficient. Instead they suggest the following
"A more common strategy is to choose an initial size for the array and add elements until it is full, then double its size and continue adding elements until it is full, and so on."
I'm having trouble wrapping my head around this. How would I got about accomplishing this?
You can double the size of an array if you multiply the lenght of your current array, like this:
array = Arrays.copyOf(array, array.lenght*2);
You have to create a new array or you can do something like :
int a[] = new a[10];
a = Arrays.copyOf(a, a.length + arrayGrowNumber);
In above example you are just copying your existing array to a new array defined with large size array.
For more information please visit this link.
Initial size for the array and add elements until it is full, then
double its size and continue adding elements until it is full, and so
on.
This is statement clearly shows to use java ArrayList as this strategy is used in ArrayList.
This is how it is declared.
List<Your_DataType> lst=new ArrayList<>();
e.g.
List<Integer> lst=new ArrayList<>();
lst.add(1);
lst.add(2);
lst.add(3);
lst.get(0);// shows 1 which is at 0th location
lst.get(1);// shows 2 which is at 0th location
lst.get(2);// shows 3 which is at 0th location
Your instructions are conflicting. The "common strategy" instructions will still "create a new array and copying the elements", but will do so less often.
Say you create the array at size 20, then begin adding a total of 50 values.
After adding first 20, you create a new array of size 40 and copy values over, then continue adding to the new array.
After adding 20 more (total of 40), you create a new array of size 80 and copy values over, then continue adding to this new array.
When you've added all 50 values, you have an array of size 80, with values in the first 50 positions. You've copied the array twice.
Saying that you cannot create a new array is misleading/wrong. You have to. The "common strategy" instruction of "double its size" requires it.

Add array to another array of larger size

I have an array A of size 5000, and a smaller array B of arbitrary size but smaller than A. My smaller array always produces new values which I do not want to loose hence I add them to the array A and continue, however I am stuck because whenever I try to copy the smaller to the larger instead of appending from where it was left of it completely erases the prior values and array A becomes equal to array B.
offset = offset + B.length;
System.arraycopy(B, 0, A, offset, B.length);
This statement is in a loop that updates B everytime.
It would be a much better idea to use ArrayLists instead. An ArrayList is essentially an array with infinite capacity. You can just keep adding stuff and it will never run out of room. It also adds things to the end for you, without you having to compute the end index. So, if you make A and B ArrayLists, then your code becomes the following:
A.addAll(B);
That's it.
First of all, take a look at this link, and look at the section explaining the length parameter: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/System.html. I think your problem resides in the length argument being passed in.
Also the statement offset = offset + B.length; should come after the loop, because you are passing in a variable size A.length + B.length, as supposed to just B.length, which is were you want to place array B.
the argument where A is is the destination array. So you have to redeclare A to be the length of offset.
Hope this helps.

Merging sorted arrays without using a sort function in Java

I have an assignment question that I need to solve without using a 'sort' commmand. I would appreciate any advice.
QUESTION: Suppose you have two arrays of ints, arr1 and arr2, each containing integers that are sorted in ascending order.
Write a static method named merge that recieves these two arrays a parameters and returns a reference to a new, sorted array of ints that is the result of merging the ints of arr and arr2.
Look into merge sort.
Pseudocode:
1: Set two pointers to beginning of the two arrays.
2: Compare the values from the two arrays at the pointers.
3: Add the smaller value to a new array and move its pointer to the next value in the array.
4: Repeat till both pointers cross the ends of the two arrays.
easy, this is the final step of the merge sort algorithm. make 2 integer variables to keep track of the index for each different input array.
Then loop through as many times as there are elements adding the minimum(or maximum depending on your sort order) out of the 2 first elements in the input arrays. This way on each iteration the smallest possible value is added to the return array. Just make sure to check that your first input array index is still less than the first input array length, if it is not then you know the rest of the elements to add are in the second input array. Increment the index for whichever array you took the element from, and increment your index for the overall array of values then.
If you need extra points or if you are bored: the relatively new Timsort algorithm uses a slightly improved merge function for the case where data is clustered (which is relatively common). This is documented in http://svn.python.org/projects/python/trunk/Objects/listsort.txt - search for "galloping mode". The galloping mode is also used in the Java implementation of timsort.

Categories