8 Replies - 231 Views - Last Post: 19 December 2014 - 08:41 PM Rate Topic: -----

#1 BBladem83  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 16-December 14

Calling Sorting Methods in Main Class

Posted 19 December 2014 - 07:49 PM

For reference I am programming Java in BlueJ.

I am fairly new to the language and I am having trouble with sorting.

I am trying to call / test all of the 5 sorting methods (at the same time) in the main class.
To be specific, the sorted list has to technically outputted 5 times.

I figured out how to call / test Quicksort:

Sorting.quickSort(friends, 0, friends.length-1);


But the others are not working correctly. Specifically these:

    Sorting.mergeSort(friends, 0, friends.length-1);
             
    Sorting.PbubbleSort(friends, 0, friends.length-1);
      
    Sorting.PinsertionSort(friends, 0, friends.length-1);
      
    Sorting.selectionSort(friends, 0, friends.length-1);


Hopefully somebody can assist me.

For reference, this is the output when it is not sorted:

    Smith, John	    610-555-7384
    Barnes, Sarah	215-555-3827
    Riley, Mark	    733-555-2969
    Getz, Laura	    663-555-3984
    Smith, Larry	464-555-3489
    Phelps, Frank	322-555-2284
    Grant, Marsha	243-555-2837


This is the output when it is sorted:

    Barnes, Sarah	215-555-3827
    Getz, Laura	    663-555-3984
    Grant, Marsha	243-555-2837
    Phelps, Frank	322-555-2284
    Riley, Mark	    733-555-2969
    Smith, John	    610-555-7384
    Smith, Larry	464-555-3489


This is the class Sorting, which I should note is all correct:

     public class Sorting{
        /**
	     * Swaps to elements in an array. Used by various sorting algorithms.
	     * 
	     * @param data the array in which the elements are swapped
	     * @param index1 the index of the first element to be swapped
	     * @param index2 the index of the second element to be swapped
	     */
	    private static <T extends Comparable<? super T>> void swap(T[] data,
			    int index1, int index2){
		    T temp = data[index1];
		    data[index1] = data[index2];
		    data[index2] = temp;
	    }

        /**
         * Sorts the specified array of objects using the quick sort algorithm.
	     * @param data the array to be sorted
	     */
	    public static <T extends Comparable<? super T>> void quickSort(T[] data){
		    quickSort(data, 0, data.length - 1);
	    }

	    /**
	     * Recursively sorts a range of objects in the specified array using the
	     * quick sort algorithm. The parameters min and max represent the range of
	     * values on which the sort is performed.
	     * 
	     * @param data the array to be sorted
	     * @param min the minimum index in the range to be sorted
	     * @param max the maximum index in the range to be sorted
	     */
	    public static <T extends Comparable<? super T>> void quickSort(T[] data,
			    int min, int max){
		    if (min < max){
			    // create partitions
			    int indexofpartition = partition(data, min, max);

			    // sort the left partition (lower values)
			    quickSort(data, min, indexofpartition - 1);

			    // sort the right partition (higher values)
			    quickSort(data, indexofpartition + 1, max);
		    }
	    }

	    /**
	     * Used by the quick sort algorithm to find the partition.
	     * 
	     * @param data the array to be sorted
	     * @param min the minimum index in the range to be sorted
	     * @param max the maximum index in the range to be sorted
	     */
	    private static <T extends Comparable<? super T>> int partition(
			    T[] data, int min, int max){
	       T partitionelement;
	       int left, right;
	       int middle = (min + max) / 2;

	       // use the middle data value as the partition element
	       partitionelement = data[middle];
	       // move it out of the way for now
	       swap(data, middle, min);

	       left = min;
	       right = max;

	       while (left < right){
	          // search for an element that is > the partition element
	          while (left < right && data[left].compareTo(partitionelement) <= 0)
		         left++;

	          // search for an element that is < the partition element
		      while (data[right].compareTo(partitionelement) > 0)
		         right--;

	          // swap the elements
		      if (left < right)
		         swap(data, left, right);
		    }

	       // move the partition element into place
	       swap(data, min, right);

	       return right;
	    }
	
	    /**
        * Sorts the specified array of objects using the merge sort
        * algorithm.
        *
        * @param data  the array to be sorted
        * @param min   the integer representation of the minimum value 
        * @param max   the integer representation of the maximum value
        */
        public static <T extends Comparable<? super T>> void mergeSort (T[] data, int min, int max){
           T[] temp;
           int index1, left, right;

           /** return on list of length one */
           if (min==max)
              return; 

           /** find the length and the midpoint of the list */
           int size = max - min + 1;
           int pivot = (min + max) / 2;
           temp = (T[])(new Comparable[size]);
      
           mergeSort(data, min, pivot); // sort left half of list
           mergeSort(data, pivot + 1, max); // sort right half of list

           /** copy sorted data into workspace */
           for (index1 = 0; index1 < size; index1++)
              temp[index1] = data[min + index1];
      
           /** merge the two sorted lists */
           left = 0;
           right = pivot - min + 1;
           for (index1 = 0; index1 < size; index1++){
              if (right <= max - min)
                 if (left <= pivot - min)
                    if (temp[left].compareTo(temp[right]) > 0)
                       data[index1 + min] = temp[right++];
               
                    else
                       data[index1 + min] = temp[left++];
                 else
                    data[index1 + min] = temp[right++];
              else
                 data[index1 + min] = temp[left++];
           }
        }

        public static <T extends Comparable<? super T>> void PbubbleSort(T[] theArray, int n) {
           // ---------------------------------------------------
           // Sorts the items in an array into ascending order.
           // Precondition: theArray is an array of n items.
           // Postcondition: theArray is sorted into ascending
           // order.  From Prichard&Carrano
           // ---------------------------------------------------
           boolean sorted = false;  // false when swaps occur

           for (int pass = 1; (pass < n) && !sorted; ++pass) {
              // Invariant: theArray[n+1-pass..n-1] is sorted
              //            and > theArray[0..n-pass]
              sorted = true;  // assume sorted
              for (int index = 0; index < n-pass; ++index) {
                 // Invariant: theArray[0..index-1] <= theArray[index]
                 int nextIndex = index + 1;
                 if (theArray[index].compareTo(theArray[nextIndex]) > 0) {
                    // exchange items
                    T temp = theArray[index];
                    theArray[index] = theArray[nextIndex];
                    theArray[nextIndex] = temp;
                    sorted = false;  // signal exchange
                 }  // end if
              }  // end for

              // Assertion: theArray[0..n-pass-1] < theArray[n-pass]
           }  // end for
        }  // end bubbleSort
   
        public static <T extends Comparable<? super T>> void PinsertionSort(T[] theArray, int n) {
           // ---------------------------------------------------
           // Sorts the items in an array into ascending order.
           // Precondition: theArray is an array of n items.
           // Postcondition: theArray is sorted into ascending
           // order. FROM PRITCHARD & CARRANO
           // ---------------------------------------------------
           // unsorted = first index of the unsorted region,
           // loc = index of insertion in the sorted region,
           // nextItem = next item in the unsorted region

           // initially, sorted region is theArray[0],
           //          unsorted region is theArray[1..n-1];
           // in general, sorted region is theArray[0..unsorted-1],
           //          unsorted region is theArray[unsorted..n-1]

           for (int unsorted = 1; unsorted < n; ++unsorted) {
              // Invariant: theArray[0..unsorted-1] is sorted

              // find the right position (loc) in
              // theArray[0..unsorted] for theArray[unsorted],
              // which is the first item in the unsorted
              // region; shift, if necessary, to make room
              T nextItem = theArray[unsorted];
              int loc = unsorted;

              while ((loc > 0) &&
                    (theArray[loc-1].compareTo(nextItem) > 0)) {
                 // shift theArray[loc-1] to the right
                 theArray[loc] = theArray[loc-1];
                 loc--;
              }  // end while
              // Assertion: theArray[loc] is where nextItem belongs
              // insert nextItem into sorted region
              theArray[loc] = nextItem;
           }  // end for
        }  // end insertionSort 
   
        public static <T extends Comparable<? super T>> void selectionSort (T[] data){
           int min;
           T temp;
      
           for (int index = 0; index < data.length-1; index++){
              min = index;
              for (int scan = index+1; scan < data.length; scan++)
                 if (data[scan].compareTo(data[min])<0)
                    min = scan;

              /** Swap the values */
              temp = data[min];
              data[min] = data[index];
              data[index] = temp;
           }
        }
    }


This is the Main class in which I am supposed to call the sorting methods, SortPhoneList:

    public class SortPhoneList{
       /**
        * Creates an array of Contact objects, sorts them, then prints
        * them.
        */
       public static void main (String[] args){
      
          Contact[] friends = new Contact[7];

          friends[0] = new Contact ("John", "Smith", "610-555-7384");
          friends[1] = new Contact ("Sarah", "Barnes", "215-555-3827");
          friends[2] = new Contact ("Mark", "Riley", "733-555-2969");
          friends[3] = new Contact ("Laura", "Getz", "663-555-3984");
          friends[4] = new Contact ("Larry", "Smith", "464-555-3489");
          friends[5] = new Contact ("Frank", "Phelps", "322-555-2284");
          friends[6] = new Contact ("Marsha", "Grant", "243-555-2837");


          Sorting.quickSort(friends, 0, friends.length-1);

          Sorting.mergeSort(friends, 0, friends.length-1);
             
          Sorting.PbubbleSort(friends, 0, friends.length-1);
      
          Sorting.PinsertionSort(friends, 0, friends.length-1);
      
          Sorting.selectionSort(friends, 0, friends.length-1);


          for (int index = 0; index < friends.length; index++)
             System.out.println (friends[index]);
       }


I seem to be really stuck here. Hoping someone can help me out.

Thank you in advance! :)/>

Is This A Good Question/Topic? 0
  • +

Replies To: Calling Sorting Methods in Main Class

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10816
  • View blog
  • Posts: 40,315
  • Joined: 27-December 08

Re: Calling Sorting Methods in Main Class

Posted 19 December 2014 - 07:53 PM

Define: "not working." Are you encountering any errors? If so, please post them exactly as they appear.

Though I would guess the problems are:
1) The selectionSort() method only accepts the array. So only pass it the array.

2) The bubbleSort() and insertionSort() methods accepts two parameters: T[] array, int n. So pass them only the array and an int.

Note: Please make sure to try my suggestions. Error messages are appreciated, but definitely use my suggestions before reporting back.
Was This Post Helpful? 0
  • +
  • -

#3 BBladem83  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 16-December 14

Re: Calling Sorting Methods in Main Class

Posted 19 December 2014 - 08:05 PM

By not working I mean not working as intended. No errors when I compile with just what I have for quicksort and mergesort (and comment out the other three calls), I only get one output, instead of two. I can only assume it is something with the mergesort call, as the quicksort call is correct.

To specify, this is all I get when I run it with quicksort and mergesort:

Barnes, Sarah	215-555-3827
Getz, Laura	663-555-3984
Grant, Marsha	243-555-2837
Phelps, Frank	322-555-2284
Riley, Mark	733-555-2969
Smith, John	610-555-7384
Smith, Larry	464-555-3489


When I uncomment the other three call methods, which are for bubbleSort, insertionSort, and selectionSort, it highlights:

Sorting.PbubbleSort(friends, 0, friends.length-1);

and gives me the error:

requried: T[],int
found: Contact[],int,int
reason: cannot infer type-variable(s) T
(actual and formal argument lists differ in length)

The operator that you use here cannot be used for the type of value that you are using it for. You are either using the wrong type here, or the wrong operator.

Was This Post Helpful? 0
  • +
  • -

#4 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10816
  • View blog
  • Posts: 40,315
  • Joined: 27-December 08

Re: Calling Sorting Methods in Main Class

Posted 19 December 2014 - 08:08 PM

None of your methods should print anything, so there is that.

I addressed the error regarding Bubblesort already. Did you read my post and try my suggestion as I asked?
Was This Post Helpful? 0
  • +
  • -

#5 BBladem83  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 16-December 14

Re: Calling Sorting Methods in Main Class

Posted 19 December 2014 - 08:13 PM

Oh yes I know that. I believe this:

      for (int index = 0; index < friends.length; index++)
         System.out.println (friends[index]);


From the main class, prints them.

I read your suggestion (which I greatly appreciate), I'm just trying to figure out what T[] array, int n would equate to, now.
Was This Post Helpful? 0
  • +
  • -

#6 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10816
  • View blog
  • Posts: 40,315
  • Joined: 27-December 08

Re: Calling Sorting Methods in Main Class

Posted 19 December 2014 - 08:16 PM

T[] array would equate to your array friends. Based on the comments for Pbubblesort:

Quote

// Precondition: theArray is an array of n items

Was This Post Helpful? 0
  • +
  • -

#7 BBladem83  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 16-December 14

Re: Calling Sorting Methods in Main Class

Posted 19 December 2014 - 08:29 PM

I wrote:

Sorting.PbubbleSort(friends, 0);


And it compiled fine, same thing with:

Sorting.PinsertionSort(friends, 0);


Not sure if it is correct though, since obviously it compiling fine doesn't equate to it being correct.

I also made:

Sorting.selectionSort(friends);


And it compiled fine.

Assuming they are correct, I just have to figure out how to make the output print 5 times based of the 5 calls.

Do I just copy paste this 5 times? I'm guessing it is not that easy haha:

for (int index = 0; index < friends.length; index++)
    System.out.println (friends[index]);


Sorry for the double post, but unfortunately I cannot edit my posts with my post count.

Anyways, I tested all the calls individually, and all of them sort correctly except for bubble sort and insert sort. I'm assuming the error lies in the int n.
Was This Post Helpful? 0
  • +
  • -

#8 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10816
  • View blog
  • Posts: 40,315
  • Joined: 27-December 08

Re: Calling Sorting Methods in Main Class

Posted 19 December 2014 - 08:31 PM

View Postmacosxnerd101, on 19 December 2014 - 10:16 PM, said:

T[] array would equate to your array friends. Based on the comments for Pbubblesort:

Quote

// Precondition: theArray is an array of n items

By passing 0, you are saying that the array has 0 elements in it. So does it really make sense to pass 0? Read the code for Sorting as well, including the comments. Actually, just focus on the comments for each method.

Quote

Do I just copy paste this 5 times? I'm guessing it is not that easy haha:

Once after each call to the sorting method. Also, you could define a method yourself to handle printing an array.
Was This Post Helpful? 0
  • +
  • -

#9 BBladem83  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 16-December 14

Re: Calling Sorting Methods in Main Class

Posted 19 December 2014 - 08:41 PM

Ohhh, so instead of 0 I pass through

friends.length


aka 7 for them.

Thanks a lot!!!!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1