How to merge an int array then put it in ascending order without any Java APIs
This is what I have:
Code Java:
package challengespackage;
public class ArrayMerge {
public static void main(String[] args) {
System.out.print(merge(new int[] { 9, 3, 0 }, new int[] { 4, 7, 8 }));
}
private static int[] merge(int[] iArrOne, int[] iArrTwo) {
int[] iArrMerged = new int[iArrOne.length + iArrTwo.length];
for (int i = 0; i < iArrOne.length; i++) {
iArrMerged[i] = iArrOne[i];
}
for (int j = 0; j < iArrTwo.length; j++) {
iArrMerged[iArrOne.length + j] = iArrTwo[j];
}
return iArrMerged;
}
}
So far all it does is combine to two arrays. I am unsure of how to sort the array in ascending order without using any Java APIs like Arrays.sort();. Any help is appreciated!
Re: How to merge an int array then put it in ascending order without any Java APIs
Are the two arrays guaranteed to be sorted before you merge them?
If not, you can either sort each array separately and then merge them, or merge the two arrays and then sort them. There's not much difference if neither array is sorted to begin with (probably simply combine the two arrays together and then sort would be easier).
If one or both of the arrays are already sorted, then you want to make sure both arrays are sorted.
Once you've got the two arrays sorted, there's a merge algorithm provided here (scroll part way down the page). You could even use the complete merge sort algorithm to sort your two arrays, and then just call the merge function to merge your two arrays together.
Re: How to merge an int array then put it in ascending order without any Java APIs
Take your pick of a sorting algorithm: Sorting Algorithms. You could as well sort them as you place them in, using a modified form of the above algorithms.
Re: How to merge an int array then put it in ascending order without any Java APIs
Thanks for the replies! I will check into those.
To provide more insight on the thread, the numbers aren't in any order. What the function merge is supposed to do is:
combine both arrays into one array - I got this
sort the combined array into ascending order - This is what I am not sure how to do
I am not allowed to use any APIs like Arrays.sort though.
Re: How to merge an int array then put it in ascending order without any Java APIs
Quote:
Originally Posted by
JBow94
Arrays.sort though.
Hmm, I was just about to ask that question
Well you could just generate the effect yourself you need to check for the lowest, and keep looping till your new array is the size of the original:
Code :
//Time
public static int[] sort(int[] unsorted) {
int[] sorted = new int[unsorted.length];
boolean[] usedIndex = new boolean[unsorted.length];
int size = 0;
while(size != unsorted.length) {
int lowest = Integer.MAX_VALUE;
int finalCur = -1;
for(int x = 0; x != unsorted.length; x++) {
if(!usedIndex[x]) {
if(lowest > unsorted[x]) {
lowest = unsorted[x];
finalCur = x;
}
}
}
usedIndex[finalCur] = true;
sorted[size++] = lowest;
}
return sorted;
}