Sort an array in Java

后端 未结 17 1244
傲寒
傲寒 2020-11-22 04:53

I\'m trying to make a program that consists of an array of 10 integers which all has a random value, so far so good.

However, now I need to sort them in order from l

17条回答
  •  感动是毒
    2020-11-22 05:13

    It may help you understand loops by implementing yourself. See Bubble sort is easy to understand:

    public void bubbleSort(int[] array) {
        boolean swapped = true;
        int j = 0;
        int tmp;
        while (swapped) {
            swapped = false;
            j++;
            for (int i = 0; i < array.length - j; i++) {
                if (array[i] > array[i + 1]) {
                    tmp = array[i];
                    array[i] = array[i + 1];
                    array[i + 1] = tmp;
                    swapped = true;
                }
            }
        }
    }
    

    Of course, you should not use it in production as there are better performing algorithms for large lists such as QuickSort or MergeSort which are implemented by Arrays.sort(array)

提交回复
热议问题