Error with Selectionsort

Total Post:51


 1287  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);

  1. 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.

      Modified On Mar-31-2018 05:24:09 AM


Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.