Home > DeveloperSection > Forums > Error with Selectionsort
Hugh Jackman
Hugh Jackman

Total Post:52

Posted on    October-05-2013 3:46 AM

 Java Java 

 1 Reply(s)
 625  View(s)
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++)
    Integer[] array = list.toArray(new Integer[list.size()]);
    for (int i = 0; i < array.length; 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;
public static void main(String args[]) {
    int number = 10;
    Integer[] list = createArray(number);


Garry Winogrand
Garry Winogrand

Total Post:24

Posted on    October-05-2013 4:26 AM

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.

Don't want to miss updates? Please click the below button!

Follow MindStick