Sorting sorting for paired in java

I wrote a selection sorting method for ints, but right now I'm working with an array of doubles. I tried changing the variables to paired, but I still get "Can't 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

    }
}
+4
source share
3 answers

The problem is that you also used double to index arrays. So try this:

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 the doubles parameter, and temp-value and arr-array also still double, but the indexes that are used for the array are ints.

int. , , - ints :

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
+6

for ?

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

int .

0

You must use the index value as an int to check this. Use it as

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

access array values ​​using these

0
source

Source: https://habr.com/ru/post/1618130/


All Articles