How to sort an array in a single loop?

后端 未结 22 2955
面向向阳花
面向向阳花 2020-12-19 09:14

So I was going through different sorting algorithms. But almost all the sorting algorithms require 2 loops to sort the array. The time complexity of Bubble sort & Insert

22条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-19 09:46

    public class SinleLoopeSorting {

    public static void main(String[] args) {
        Integer[] x = new Integer[] { 1, 7, 8, 0, 4, 2, 3 };
    
        for (int i = 0; i < x.length - 1; i++) {
            if (x[i] > x[i + 1]) {
                int p = x[i];
                x[i] = x[i + 1];
                x[i + 1] = p;
                i = -1;
            }
        }
        for (int i = 0; i < x.length; i++) {
            System.out.println(x[i]);
        }
    }
    

    }

提交回复
热议问题