Java : Sort integer array without using Arrays.sort()

后端 未结 12 2608
滥情空心
滥情空心 2021-02-14 00:59

This is the instruction in one of the exercises in our Java class. Before anything else, I would like to say that I \'do my homework\' and I\'m not just being lazy asking someon

12条回答
  •  一整个雨季
    2021-02-14 01:29

    Bubble sort can be used here:

     //Time complexity: O(n^2)
    public static int[] bubbleSort(final int[] arr) {
    
        if (arr == null || arr.length <= 1) {
            return arr;
        }
    
        for (int i = 0; i < arr.length; i++) {
            for (int j = 1; j < arr.length - i; j++) {
                if (arr[j - 1] > arr[j]) {
                    arr[j] = arr[j] + arr[j - 1];
                    arr[j - 1] = arr[j] - arr[j - 1];
                    arr[j] = arr[j] - arr[j - 1];
                }
            }
        }
    
        return arr;
    }
    

提交回复
热议问题