#how can i make my selection sort code shorter

1 messages · Page 1 of 1 (latest)

austere steppe
#

Something feels off about my code but im not sure whatq


public static void sort(int[] array) {
        int index = 0;
        while (index < array.length) {
            int smallest = Integer.MAX_VALUE;
            int smallestIndex = -1;

            for (int i = index; i < array.length; i++) {
                if (smallest > array[i]) {
                    smallest = array[i];
                    smallestIndex = i;
                }
            }
            int temp = array[smallestIndex];
            array[smallestIndex] = array[index];
            array[index] = temp;
            index++;
        }
    }

exotic fractalBOT
#

<@&987246399047479336> please have a look, thanks.

mellow dew
mellow dew
#

I dont see the point in it for insertion sort

solemn harbor
#

There is no check for array == null.

raw mason
#

That's selection sort btw, not insertion sort

#
    public static void sort(int[] array) {
        for (int index = 0; index < array.length - 1; index++) {
            int smallest = array[index];
            int smallestIndex = -1;

            for (int i = index + 1; i < array.length; i++) {
                if (array[i] < smallest) {
                    smallest = array[i];
                    smallestIndex = i;
                }
            }

            int temp = array[smallestIndex];
            array[smallestIndex] = array[index];
            array[index] = temp;
        }
    }
#

This should still work

austere steppe
#

how can i make my selection sort code shorter

austere steppe
#

lemme check rq though

raw mason
#

but yeah, your're doing the least amount of stuff possible pretty much

#

smallestIndex should be index, not -1

#
    public static void sort(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            int min = array[i];
            int minIdx = i;

            for (int j = i + 1; j < array.length; j++) {
                if (array[j] < min) {
                    min = array[j];
                    minIdx = j;
                }
            }

            int temp = array[minIdx];
            array[minIdx] = array[i];
            array[i] = temp;
        }
    }
austere steppe
#

oh shoot it does work

#

damnn

raw mason
#

yeah, if you have only one item, that's the minimum, and that's also the minimum of the one item list you're going to compare

#

so you can skip a few extra steps

austere steppe
#

oh wait ik why i thought my code was off its cause i was looking at insertion sort code instead of selection sort

#

so it looked shorter

raw mason
#

This is pretty much this exactly

#

yeah, insertion sort is shorter, but selection sort is easier to think about 😄

austere steppe
#

ohhh alright

austere steppe
#

alright thanks for the help :DDD