Solved

Sorting

Posted on 2003-12-01
12
505 Views
Last Modified: 2008-02-01
Hello,

I'm trying to test the insertionSort, quickSort, and mergeSort but I'm getting compilation errors on parts of my program.  Below are the two methods (I think...) that are giving the errors:
-----------------------------------------------------------

private static void choosePivot(Comparable[] theArray, int first, int last) {

      int pivotIndex;
      int mid = (first + last)/2;
            if (theArray[first] <= theArray[mid]) {
                  if (theArray[mid] <= theArray[last]) {
                       pivotIndex = mid;
                  }
                  else {
                       pivotIndex = (theArray[first] <= theArray[last] ? last:first);
                  }
            }
            else if(theArray[last] <= theArray[mid]) {
                 pivotIndex = mid;
            }
            else {
                 pivotIndex = (theArray[first] <= theArray[last] ? first:last);
                 swap(theArray[first], theArray[pivotIndex]);
            }

}  // end choosePivot

//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//

 public void swap(int left, int right) {

         Comparable temp = theArray[left];
         theArray[left] = theArray[right];
         theArray[right] = temp;

 } // end swap()

-----------------------------------------------------

Can someone also explain what 'Comparable' is and what it does... because I get the following compilation errors:

operator <= cannot be applied to java.lang.Comparable,java.lang.Comparable  
                        - and -
swap(int,int) cannot be applied to (java.lang.Comparable,java.lang.Comparable)

----------------------------------------------------

Also, the compiler's complaing that it can't find 'theArray' in my swap method:

cannot resolve symbol: Comparable temp = theArray[left];
                                                                     ^

----------------------------------------------------

If you need the rest of my program, please let me know.  Thanks :)
0
Comment
Question by:luna621
  • 7
  • 5
12 Comments
 
LVL 92

Expert Comment

by:objects
ID: 9856193
Comparable is an interface that defines how to compare objects.
It includes one method:
int compareTo(Object o)
See the javadoc for more details.

in your case to use it, instead of:
 if (theArray[first] <= theArray[mid]) {
you would do:
 if (theArray[first].compareTo(theArray[mid])<=0) {
0
 
LVL 92

Expert Comment

by:objects
ID: 9856202
> cannot resolve symbol: Comparable temp = theArray[left];

You need to pass theArray to your swap() method.

public void swap(int[] theArray, int left, int right) {
0
 

Author Comment

by:luna621
ID: 9856767
Yay!  It worked for the swap method, but how do I ".compareTo" for these?  Someone told me to write the ? : form, but I don't understand what that is... can you please explain?  
------------------------------------------------------------------------------------
            else {
            pivotIndex = (theArray[first] <= theArray[last] ? last:first);
            }
      }
      else if(theArray[last].compareTo(theArray[mid])<=0) {
            pivotIndex = mid;
      }
      else {
            pivotIndex = (theArray[first] <= theArray[last] ? first:last);
            swap(theArray[first], theArray[pivotIndex]);
      }

-----------------------------------------------------------------------------------

I also get this error:

swap(java.lang.Comparable[],int,int) cannot be applied to (java.lang.Comparable,java.lang.Comparable)

swap(theArray[first], theArray[pivotIndex]);

What does that mean?  Thank you!
0
 
LVL 92

Expert Comment

by:objects
ID: 9856815
> pivotIndex = (theArray[first] <= theArray[last] ? last:first);

pivotIndex = (theArray[first].compareTo(theArray[last])<=0 ? last : first);

> swap(java.lang.Comparable[],int,int) cannot be applied to (java.lang.Comparable,java.lang.Comparable)

you need to pass the array as you have now added it as a param
you also should be passing the index not the array value

swap(theArray, first pivotIndex);
0
 

Author Comment

by:luna621
ID: 9864738
Yay!  It worked!  Okay, but now I'm testing the program.  Is there a way I can have random integers and Strings sorted through my program?  Is there a way to time how long it takes?

Here's my main method so far...
---------------------------------------

      public static void main(String args[]){

            long start = System.currentTimeMillis();
            Date startTime = new Date(start);

            System.out.println(startTime.toString());

//-------------------------------------------
// start testing... need to input random
// numbers and integers here.
//-------------------------------------------



            long stop = System.currentTimeMillis();
            Date stopTime = new Date(stop);

            System.out.println(stopTime.toString());


//-------------------------------------------
// find out how much time spent...
//-------------------------------------------

            Date totalTime = (stopTime - startTime);

      } // end main()

-------------------------------------------------

I seem to have a problem with this line:  Date totalTime = (stopTime - startTime);

It's giving me this error:  operator - cannot be applied to java.util.Date,java.util.Date

-------------------------------------------------

I believe this is the compacted version of something...

pivotIndex = (theArray[first] <= theArray[last] ? last:first);

Is there another way to write the above (without the question mark, etc.)?

-------------------------------------------------

Sorry for asking so many questions.  This is like a 3-in-1 question!  To be fair, I increased the points :)

-luna621 =^_^=

0
 
LVL 92

Accepted Solution

by:
objects earned 350 total points
ID: 9864764
> Date totalTime = (stopTime - startTime);

startTime and stopTime are longs, it should be:

long totalTime = (stopTime - startTime);

> pivotIndex = (theArray[first] <= theArray[last] ? last:first);
> Is there another way to write the above (without the question mark, etc.)?

Its called a ternary operator: <condition> ? <value> : <value>
It is equivalent to:

if (theArray[first] <= theArray[last])
{
   pivotIndex = last;
}
else
{
   pivotIndex = first;
}
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:luna621
ID: 9871890
Is there a way for me to have RANDOM integers read into the different sort methods?  Can I do the same for Strings?  Do I need to import anything (i.e. import java.util.*;)?
0
 
LVL 92

Expert Comment

by:objects
ID: 9871932
java.util.Random can be used for generating Random numbers.
0
 

Author Comment

by:luna621
ID: 9872031
I want to do something like this in my main to compare the execution times of each sorting method:

- Timings of insertionSort, quickSort, & mergeSort -

 Number of (random) elements: #####

insertionSort execution time in millisecs: #####
     quickSort execution time in millisecs: #####
   mergeSort execution time in millisecs: #####

----------------------------------

How would I make it sort the random ints & Strings?  My insertionSort method is:

public static void insertionSort(Comparable[] theArray, int n) {
...
}

Do I write it like this: insertionSort(???, Math.random());

I don't know what to put for the ??? part.  Because the method calls for a Comparable[] theArray... am I suppose to make an array with random ints?  How do I make that Comparable?
0
 
LVL 92

Expert Comment

by:objects
ID: 9872053
You create your array to sort and then fill it with random numbers using Random.

arr = new Comparable[10];
for (int i=0; i<arr.length; i++)
{
   arr[i] = new Integer(myrandom.nextInt());
}
insertionSort(arr, arr.length);
0
 

Author Comment

by:luna621
ID: 9872696
I think I got it!  Thank you very much!

-luna621 =^_^=
0
 
LVL 92

Expert Comment

by:objects
ID: 9872722
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now