homidhomi4
homidhomi4

Reputation: 123

Selection sort for doubles in java

I have written the selection sort method before for ints, but right now I am working with an array of doubles. I have tried changing the variables to doubles, but I am still getting a "Cannot convert from double to int". Any help is appreciated, thanks!

//Original selection sort for ints
public static void selectionSort (int... arr)
{
    int i = 0, j = 0, smallest = 0;
    int temp = 0;

    for (i = 0;i<arr.length - 1;i++)
    {
        smallest = i;
        for (j = 1; j<arr.length - 1; j++)
        {
            if (arr[j]<arr[smallest])
                smallest = j;
        }
        temp = arr[smallest];
        arr[smallest] = arr[i];
        arr[i] = temp;

    }
}

//Attempted selection sort with doubles
public static void selectionSort (double...arr )
{
    double i = 0.0, j = 0.0, smallest = 0.0;
    double temp = 0.0;

    for (i = 0.0;i<arr.length - 1.0;i++)
    {
        smallest = i;
        for (j = 1.0; j<arr.length - 1.0; j++)
        {
            if (arr[j]<arr[smallest]) //error here with smallest and j
                smallest = j;
        }
        temp = arr[smallest]; //error here with smallest
        arr[smallest] = arr[i]; //error here with smallest and i
        arr[i] = temp; //error here with i

    }
}

Upvotes: 4

Views: 2058

Answers (3)

Sachin Sridhar
Sachin Sridhar

Reputation: 445

You have to use subscript value as int check out with that. Use like this

int i = 0,j =0,smallest = 0;

access array values using these

Upvotes: 0

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37584

Why did you change the for loop to doubles?

for (i = 0.0;i<arr.length - 1.0;i++)

It does only work with int's for the indexes of the arrays.

Upvotes: 0

Kevin Cruijssen
Kevin Cruijssen

Reputation: 9326

The problem is that you've also used double for indexing the arrays. So try this instead:

public static void selectionSort (double...arr)
{
    int i = 0, j = 0, smallest = 0;
    double temp = 0.0;

    for (i = 0; i < arr.length - 1; i++)
    {
        smallest = i;
        for (j = 1; j < arr.length - 1; j++)
        {
            if (arr[j] < arr[smallest])
                smallest = j;
        }
        temp = arr[smallest];
        arr[smallest] = arr[i];
        arr[i] = temp;
    }
}

As you can see you still have doubles as parameter, and the temp-value and arr-array are also still doubles, but the indexes that are used for the array are ints.

Indexes are always int. For example, when we have an array of Strings, we still use ints for the indexes:

String[] sArray = {
    "word1",
    "word2",
    "word3"
}
int index = 1;
String result = sArray[index]; // As you can see we use an int as index, and the result is a String
// In your case, the index is still an int, but the result is a double

Upvotes: 6

Related Questions