bubble sort with a boolean to determine whether array is already sorted

自作多情 提交于 2019-12-02 07:46:05

Your bubble sort is wrong?

    private static int[] sortBuble(int[] a) {
        boolean swapped = true;
        int n = a.length;
        for (int i = 0; i < n && swapped; i++) {
            swapped = false;
            int newn = 0;
            System.out.println("number of iteration" + i);

            for (int j = 1; j < a.length; j++) {

                if (a[j-1] > a[j]) {
                    int temp = a[j-1];
                    a[j-1] = a[j];
                    a[j] = temp;
                    swapped = true;
                    newn = j;
                }
            }
            n = newn;
        }

        return a;
    }

This is essentially the same as yours, but working and more efficient:

private static int[] bubblesort(int[] nums)
{
    boolean done = false;

    for (int i = 0;  i < nums.length && !done; i++)
    {
        done = true;

        for (int j = nums.length-1; j > i; j--)
        {
            if (nums[j] < nums[j-1])
            {
                int temp = nums[j];
                nums[j] = nums[j-1];
                nums[j-1] = temp;
                done = false;
            }
        }
    }

    return nums;
}

At the end of the ith iteration, we know that the first i elements are sorted, so we don't need to look at them anymore. We need the boolean to determine if we need to continue or not. If no swaps are made, then we are done. We can remove the boolean and it will still work, but will be less efficient.

It is called flagged bubble sort. It helps to save time mainly. It checks whether the array positions are sorted. if it is sorted it breaks, and move to 2nd execution.

and the code can be rewritten as:-

for (int j = 1; j < a.length; j++) {

            if (a[j-1] > a[j]) {
                int temp = a[j-1];
                a[j-1] = a[j];
                a[j] = temp;
                swapped = true;             
            }
        }
        if(!swapped)
           break;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!