---
title: "Error with Selectionsort"  
description: "Error with Selectionsort"  
author: "Anonymous User"  
published: 2013-10-05  
updated: 2013-10-05  
canonical: https://www.mindstick.com/forum/1602/error-with-selectionsort  
category: "java"  
tags: ["java"]  
reading_time: 2 minutes  

---

# Error with Selectionsort

I [am trying](https://answers.mindstick.com/qa/36834/which-two-programming-languages-should-i-master-in-if-i-am-trying-to-get-into-google-or-facebook) to making Selectionsort but it will give an [error](https://yourviews.mindstick.com/view/88527/fixing-quickbooks-error-4120-reinstalling-vs-repairing)

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

}
}
```

## Replies

### Reply by Anonymous User

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.


---

Original Source: https://www.mindstick.com/forum/1602/error-with-selectionsort

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
