DevSE Dominik
DevSE Dominik

Reputation: 21

Using a sort algorithm in Java

I was trying to use a sort algorithm according to our programming lecture. Maybe I am just missing something.

I would appreciate it if someone may help me out or could give me a hint about any mistake I made.

Here my current code:

package Sortieralgorithmus;

public class sort {

public static int[] straightSelection(int[] numbers) {

    for (int i = 0; i < numbers.length; i++) {
        int smallestIndex = i;

        for (int j = i + 1; j < numbers.length; j++) {
            if (numbers[i] < numbers[smallestIndex]) {
                smallestIndex = j;
            }
        }
        swap(j, i, numbers);


    }

    return numbers;
}
}

Upvotes: 1

Views: 155

Answers (2)

Jobs
Jobs

Reputation: 3377

You are doing an in-place selection sort. Change

if (numbers[i] < numbers[smallestIndex]) 

to

if (numbers[j] < numbers[smallestIndex]) 

Also change

(int i = 0; i < numbers.length; i++)

to

(int i = 0; i < numbers.length()-1; i++)

Additionally, because i and j are declared within your for condition, they are only accessible within the scope of the for loop. Instead, declare them outside of your loops.

Lastly, it's a good idea to check if(smallestIndex != i) before swapping them.

So here's your working code, assuming your swap function works correctly.

package Sortieralgorithmus;

public class sort {

public static int[] straightSelection(int[] numbers) {
int i, j;  // declare them here 
int smallestIndex; //declare it here as well

for (i = 0; i < numbers.length-1; i++) {
    smallestIndex = i;

    for (j = i + 1; j < numbers.length; j++) {
        if (numbers[j] < numbers[smallestIndex]) {
            smallestIndex = j;
        }
    }
    if(smallestIndex != i){
    swap(smallestIndex, i, numbers);
    }

}

return numbers;
}
}

Please refer to the following: http://en.wikipedia.org/wiki/Selection_sort

Upvotes: 2

DevSE Dominik
DevSE Dominik

Reputation: 21

Here is my implementation of the swap command (sorry for wrong declarations I have recognized them and I will change them immediately!):

package Sortieralgorithmus;

public class Swap {

public static void swap(int a, int b, int []numbers) {

    int temp = numbers[a];
    numbers[a] = numbers[b];
    numbers[b] = temp;

}

}

Upvotes: 0

Related Questions