Home > Net >  How do I sort an array of integers from minimum to maximum value without using Arrays.sort()?
How do I sort an array of integers from minimum to maximum value without using Arrays.sort()?

Time:03-29

I'm learning how to use arrays, and I'm trying to manually sort an array of integers using two ArrayList<Integer>.

Here's what I have currently:

public Object[] arraySort (int[] importedArray) {
        // !!! This method returns the original imported method (?). !!!
        ArrayList<Integer> unsorted = new ArrayList<>();
        ArrayList<Integer> sorted = new ArrayList<>();
        // Convert importedArray into unsorted Integer ArrayList
        for (int i = 0; i < importedArray.length; i  ) {
            unsorted.add(importedArray[i]);
        }
        // Find minimum value of unsorted ArrayList, add to sorted ArrayList, and remove min value from unsorted
        for (int i = 0; i < unsorted.size(); i  ) {
            int min = Integer.MAX_VALUE;
            int index = 0;
            for (int j = 0; j < unsorted.size(); j  ) {
                if (unsorted.get(j) < min) {
                    min = unsorted.get(j);
                    index = j;
                }
            }
            unsorted.remove(index);
            sorted.add(min);
        }
        return unsorted.toArray();
    }

However, when I run the method, I get the same imported array back. The first for loop to convert int[] into ArrayList<Integer> apparently worked when I checked using print, so the problem is most likely in the second for loop.

I've also tried other insertion sorting methods, but I'm not sure what I am doing wrong with this type of sorting method. Did I totally screw up somewhere? Or is this method not possible? Thanks in advance for your help!

CodePudding user response:

First of all, you should return the sorted array and not the unsorted one. You should also be careful when using unsorted.size() in the loop header because the programm will call that method every time an iteration has finished. But since you decrease the size inside of the loop with update.remove(index), the size does not stay the same and you just skip some values. Thus, you should save that value in a variable before starting the loop. The following code worked for me:

public Object[] arraySort(int[] importedArray) {
    ArrayList<Integer> unsorted = new ArrayList<>();
    ArrayList<Integer> sorted = new ArrayList<>();
    for (int i = 0; i < importedArray.length; i  ) {
        unsorted.add(importedArray[i]);
    }
    int size = unsorted.size();
    for (int i = 0; i < size; i  ) {
        int min = Integer.MAX_VALUE;
        int index = 0;
        for (int j = 0; j < unsorted.size(); j  ) {
            if (unsorted.get(j) < min) {
                min = unsorted.get(j);
                index = j;
            }
        }
        unsorted.remove(index);
        sorted.add(min);
    }
    return sorted.toArray();
}
  • Related