George has a problem. He’s got two unordered integer arrays such as below:
{2, 3, 1}
{2, 5, 5, 8, 9, 13}
Now, he wants to merge these two and sort them in ascending order. He is not allowed to use any sort functions to solve this problem. The result should display:
[1, 2, 2, 3, 5, 5, 8, 9, 13]
His task is to define a function to merge and sort integer arrays without using pre-defined functions of Java. To solve this problem, let’s break down our solution into smaller steps.
First step is to merge:
static int[] mergeArray(int[] arr1, int[] arr2) { int[] mergedArr = new int[arr1.length + arr2.length]; int index = arr2.length; for(int i = 0; i < arr2.length; i++) { mergedArr[i] = arr2[i]; } for(int i = 0; i < arr1.length; i++) { mergedArr[i + index] = arr1[i]; } return mergedArr; }
Second step is to sort:
And then to sort it, we will implement Bubble sort algorithm. (Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. source: Wikipedia)
static int[] sortArray(int[] mergedArr) { for(int i = 0; i < mergedArr.length; i++) { for(int j = i + 1; j < mergedArr.length; j++) { int tmp = 0; if(mergedArr[i] > mergedArr[j]) { tmp = mergedArr[i]; mergedArr[i] = mergedArr[j]; mergedArr[j] = tmp; } } } return mergedArr; }
This is to sort in ascending order. If you want to sort in descending order, just change the operand from > (greater than) to < (less than).
static int[] sortArray(int[] mergedArr) { for(int i = 0; i < mergedArr.length; i++) { for(int j = i + 1; j < mergedArr.length; j++) { int tmp = 0; if(mergedArr[i] < mergedArr[j]) { tmp = mergedArr[i]; mergedArr[i] = mergedArr[j]; mergedArr[j] = tmp; } } } return mergedArr; }
And that’s it! If you want the entire code, please refer to solution below:
import java.util.Arrays; public class MyClass { public static void main(String args[]) { int[] arr1 = {2, 3, 1}; int[] arr2 = {2, 5, 5, 8, 9, 13}; System.out.print(Arrays.toString(sortArray(mergeArray(arr1, arr2)))); } static int[] mergeArray(int[] arr1, int[] arr2) { int[] mergedArr = new int[arr1.length + arr2.length]; int index = arr2.length; for(int i = 0; i < arr2.length; i++) { mergedArr[i] = arr2[i]; } for(int i = 0; i < arr1.length; i++) { mergedArr[i + index] = arr1[i]; } return mergedArr; } static int[] sortArray(int[] mergedArr) { for(int i = 0; i < mergedArr.length; i++) { for(int j = i + 1; j < mergedArr.length; j++) { int tmp = 0; if(mergedArr[i] > mergedArr[j]) { tmp = mergedArr[i]; mergedArr[i] = mergedArr[j]; mergedArr[j] = tmp; } } } return mergedArr; } }
Result:
[1, 2, 2, 3, 5, 5, 8, 9, 13]
I recommend using http://www.jdoodle.com to test it online if you don’t have any installed IDE on your local machines. If you have any questions, feel free to drop your comments 🙂
One thought on “Java merge and sort integer arrays without using pre-defined functions”