How to sort an array in a single loop?

后端 未结 22 2952
面向向阳花
面向向阳花 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条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-19 09:28

    Sorting an array using java in Single Loop:

        public int[] getSortedArrayInOneLoop(int[] arr) {
    
        int temp;
        int j;
    
            for (int i = 1; i < arr.length; i++) {
            j = i - 1;
    
                if (arr[i] < arr[j]) {
    
                temp = arr[j];
                arr[j] = arr[i];
                arr[i] = temp;
                i = 1;
    
                }
    
            }
    
        return arr;
    
        }
    

提交回复
热议问题