Optimized Bubble Sort (Java)

前端 未结 10 1217
旧时难觅i
旧时难觅i 2020-12-05 11:29

I would like to know how else I can optimize bubble sort so that it overlooks elements that have already been sorted, even after the first pass.

Eg. [4, 2, 3         


        
10条回答
  •  不知归路
    2020-12-05 12:18

    I devised a method that reduces the number of iterations by excluding parts at the beginning and end of the array that have been ordered in previous loops.

    static int[] BubbleSortOptimized(int arr[]) {
        int start = 0, stop = arr.length - 1, control = 0;
        boolean ordered, nsCaught;
        while (true){
            ordered = true;
            nsCaught = false;
            for (int i = start; i < stop; i++) {
                if (i > 1) {
                    if (!nsCaught && arr[i-2] > arr[i-1]){
                        ordered = false;
                        start = i-2;
                        nsCaught = true;
                    }
                }
                if (arr[i] > arr[i+1]){
                    int hold = arr[i];
                    arr[i] = arr[i+1];
                    arr[i+1] = hold;
                    control = i;
                }
            }
            System.out.println(Arrays.toString(arr));
            if (ordered) return arr;
            stop = control;
        }
    }
    

    But as @Daniel Fischer said in an earlier answer, it doesn't do a lot with larger arrays.

提交回复
热议问题