Advertisement
brilliant_moves

MergeArrays.java

Mar 15th, 2014
468
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.85 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class MergeArrays {
  4.  
  5.     /**
  6.     *   Program:    MergeArrays.java
  7.     *   Purpose:    Merge two sorted integer arrays into a third array.
  8.     *   Creator:    Chris Clarke
  9.     *   Created:    16.03.2014
  10.     *           Search Amazon for "50 More Java Source Codes" for more great code examples!
  11.     *           In Kindle and paperback editions.  See also "50 Java Program Source Codes".
  12.     */
  13.  
  14.     public static void main(String[] args) {
  15.         // adapt as necessary
  16.         // test data
  17.         int[] a = { 8, 3, 3, 4, 1};
  18.         int[] b = { 2, 10, 5, 2, 7, 7, 6};
  19.         int[] c;
  20.  
  21.         displayArray("Array a: ", a);
  22.         sort(a);
  23.         displayArray("Array a (sorted): ", a);
  24.  
  25.         displayArray("Array b: ", b);
  26.         sort(b);
  27.         displayArray("Array b (sorted): ", b);
  28.  
  29.         System.out.println("Merging...");
  30.  
  31.         // merge the two sorted arrays
  32.         c = merge(a, b);
  33.         // display result
  34.         displayArray("Array c: ", c);
  35.  
  36.     } // end main()
  37.    
  38.     public static void sort(int[] a) {
  39.     // apply bubblesort algorithm to array a
  40.         int i,j,temp;
  41.         int len = a.length;
  42.  
  43.         for (i=0; i<len-1; i++) {
  44.             for (j=0; j<len-1-i; j++) {
  45.                 if (a[j]>a[j+1]) {
  46.                     // swap
  47.                     temp=a[j];
  48.                     a[j]=a[j+1];
  49.                     a[j+1]=temp;
  50.                 }//end if
  51.             }//end for j
  52.         }//end for i
  53.     } //end sort()
  54.  
  55.     public static int[] merge(int[] a, int[] b) {
  56.         // merge 2 sorted arrays
  57.  
  58.         int[] c = new int[a.length + b.length];
  59.         int i=0, j=0, k=0;
  60.  
  61.         while (i<a.length && j<b.length) {
  62.             c[k++] = (a[i]<b[j]? a[i++]: b[j++]);
  63.         } // end while
  64.  
  65.         while (j<b.length) {
  66.             c[k++] = b[j++];
  67.         } // end while
  68.  
  69.         while (i<a.length) {
  70.             c[k++] = a[i++];
  71.         } // end while
  72.  
  73.         return c;
  74.     } // end merge()
  75.  
  76.     public static void displayArray(String s, int[] arr) {
  77.         // print title and contents of array
  78.         System.out.print(s);
  79.         System.out.println(Arrays.toString(arr));
  80.         System.out.println(); // new line
  81.     } // end displayArray()
  82.  
  83. } // end class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement