ERROR WITH SELECTIONSORT

Hugh Jackman

Total Post:52

Points:366
Posted by  Hugh Jackman
Java 
 903  View(s)
Ratings:
Rate this:

I am trying to making Selectionsort but it will give an error

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class Sorts {
 
public static Integer[] createArray(int size) {
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < size; i++)
        list.add(i);
    Collections.shuffle(list);
    Integer[] array = list.toArray(new Integer[list.size()]);
    for (int i = 0; i < array.length; i++) {
        System.out.print(array[i]);
    }
    return array;
 
}
 
public static void selectionSort(Integer[] array) {
    Integer min;
    for (Integer i = 0; i < array.length - 1; i++) {
        min = i;
        for (Integer j = i + 1; j < array.length; j++) {
            if (array[j].compareTo(array[min]) > 0) {
                min = j;
            }
        }
        if (min != i) {
            Integer temp = array[i];
            array[i] = array[min];
            array[min] = temp;
            System.out.print(array[i]);
 
        }
 
    }
}
 
public static void main(String args[]) {
    int number = 10;
    Integer[] list = createArray(number);
    System.out.println("");
    selectionSort(list);
 
}

}

  1. Garry Winogrand

    Post:24

    Points:168
    Re: Error with Selectionsort

    Whenever you make a swap, you print out a number. But in an array of 10 elements, you'll only make 9 swaps -- the final element will already be in its correct place! To fix this, add System.out.print(array[array.length - 1]); to the end of your function.

    Also, if the minimum element happens to be i, then no swap will be performed and no element printed. This still sorts the array, but if you want it to be printed out, you could remove the if (min != i)statement and simply do a swap on every pass through the list.

    You should also take a look at using ints rather than Integers. An Integer is generally slower than an int and you usually only use them when Java wants an object.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!