Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- public class MergeArrays {
- /**
- * Program: MergeArrays.java
- * Purpose: Merge two sorted integer arrays into a third array.
- * Creator: Chris Clarke
- * Created: 16.03.2014
- * Search Amazon for "50 More Java Source Codes" for more great code examples!
- * In Kindle and paperback editions. See also "50 Java Program Source Codes".
- */
- public static void main(String[] args) {
- // adapt as necessary
- // test data
- int[] a = { 8, 3, 3, 4, 1};
- int[] b = { 2, 10, 5, 2, 7, 7, 6};
- int[] c;
- displayArray("Array a: ", a);
- sort(a);
- displayArray("Array a (sorted): ", a);
- displayArray("Array b: ", b);
- sort(b);
- displayArray("Array b (sorted): ", b);
- System.out.println("Merging...");
- // merge the two sorted arrays
- c = merge(a, b);
- // display result
- displayArray("Array c: ", c);
- } // end main()
- public static void sort(int[] a) {
- // apply bubblesort algorithm to array a
- int i,j,temp;
- int len = a.length;
- for (i=0; i<len-1; i++) {
- for (j=0; j<len-1-i; j++) {
- if (a[j]>a[j+1]) {
- // swap
- temp=a[j];
- a[j]=a[j+1];
- a[j+1]=temp;
- }//end if
- }//end for j
- }//end for i
- } //end sort()
- public static int[] merge(int[] a, int[] b) {
- // merge 2 sorted arrays
- int[] c = new int[a.length + b.length];
- int i=0, j=0, k=0;
- while (i<a.length && j<b.length) {
- c[k++] = (a[i]<b[j]? a[i++]: b[j++]);
- } // end while
- while (j<b.length) {
- c[k++] = b[j++];
- } // end while
- while (i<a.length) {
- c[k++] = a[i++];
- } // end while
- return c;
- } // end merge()
- public static void displayArray(String s, int[] arr) {
- // print title and contents of array
- System.out.print(s);
- System.out.println(Arrays.toString(arr));
- System.out.println(); // new line
- } // end displayArray()
- } // end class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement