So I am writing a selection sort algorithm that puts turns all the parts of the sort into methods. However, when I compile it, it returns the error:
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
What am I doing wrong?
import java.io.*;
public class Driver01
{
public static void main(String[] args)
{
//input
double[] myArray = {2.0, 3.7, 9.9, 8.1, 8.5, 7.4, 1.0, 6.2};
//sort the array
double[] sorted = process(myArray);
//output
System.out.print("" + sorted);
}
private static double findMax( int EndIndex, double[] enterArray) {
double max = 0;
int trueIndex = 0;
for( int x = 0; x < EndIndex; x++) {
if(enterArray[x] > max) {
max = enterArray[x];
trueIndex = x;
}
}
return trueIndex;
}
private static void swap(int swap1, int swap2, double[] enterArray) {
double temp = 0;
temp = enterArray[swap1];
enterArray[swap1] = enterArray[swap2];
enterArray[swap2] = enterArray[swap1];
}
private static double[] process(double[] enterArray) {
int range = enterArray.length -1;
for( int x = 0; x < enterArray.length-1; x++) {
double j = findMax(range, enterArray);
swap(j, range, enterArray);
range = range -1;
}
return enterArray;
}
}
Revised Code:
import java.io.*;
public class Driver01
{
public static void main(String[] args)
{
//input
double[] myArray = {2.0, 3.7, 9.9, 8.1, 8.5, 7.4, 1.0, 6.2};
//sort the array
double[] sorted = process(myArray);
//output
System.out.print("" + sorted);
}
private static int findMax( int EndIndex, double[] enterArray) {
double max = 0;
int trueIndex = 0;
for( int x = 0; x < EndIndex; x++) {
if(enterArray[x] > max) {
max = enterArray[x];
trueIndex = x;
}
}
return trueIndex;
}
private static void swap(int swap1, int swap2, double[] enterArray) {
double temp = 0;
temp = enterArray[swap1];
enterArray[swap1] = enterArray[swap2];
enterArray[swap2] = enterArray[swap1];
}
private static double[] process(double[] enterArray) {
int range = enterArray.length -1;
for( int x = 0; x < enterArray.length-1; x++) {
int j = findMax(range, enterArray);
swap(j, range, enterArray);
range = range -1;
}
return enterArray;
}
}
Now the code is printing an array that looks like this: [D@15db9742 What's wrong now?
The full error message is:
Driver01.java:41: error: incompatible types: possible lossy conversion
from double to int
swap(j, range, enterArray);
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose
to get full output
1 error
From this, it is clear that you are calling swap
with a double
argument when it is expecting an int
argument.
Now I am not going to suggest a solution, but I would advise you to carefully look at what findMax
is doing and what it is returning. Particularly the return type!
(Part of the problem here is that the name of the findMax
variable is misleading. The method doesn't do what the name implies that it does.)