1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Testing a Program

  1. Feb 7, 2005 #1
    Hello all

    Let's say we have the following classes:

    Code (Text):
     public class Merge {
    protected static void merge(int[] a, int first, int last, int middle) {

            int i, j, k;
            int[] tempArray = new int[a.length];
            i = first;
            j = first;
            k = middle + 1;

            while(j <= middle && k <= last){
                if(a[j] <= a[k])
                    tempArray[i++] = a[j++];
                else
                    tempArray[i++] = a[k++];
            }
            while(j <= middle)
                tempArray[i++] = a[j++];
            while(k <= last)
                tempArray[i++] = a[k++];

            for (i = first; i <= last; i++)
                a[i] = tempArray[i];
            }
        }
     
    and

    Code (Text):
     public class MergeSort extends Merge {
    public static void mergeSort(int[] a, int first, int last) {

            if(last==first) return;
            if (last - first == 1) {
                //  not a[0]>a[1]; this part could test on the upper half of the array
                if (a[first] > a[last]) {
                    int temp = a[first];
                    a[first] = a[last];
                    a[last] = temp;
                }
               

            } else {
                int halfwayPoint = (int) (last + first) / 2;
                mergeSort(a, first, halfwayPoint);
                mergeSort(a, halfwayPoint + 1, last);
                merge(a, first, last, halfwayPoint);
               
            }
        }
    }
     
    How would I print the array? I am stuck. I wrote the two classes but dont know how to get the output. Do I need a for loop?

    Thanks :smile:
     
  2. jcsd
  3. Feb 7, 2005 #2
    Yeah, just use a for loop to go through each element in turn and print using System.out.println():

    Code (Text):
    for(int i = 0; i < array.length(); i++)
    [indent]System.out.println(array[i]);[/indent]
    HTH.
     
  4. Feb 7, 2005 #3
    thanks a bunch :smile:
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook




Loading...