How to sort an array in a single loop?

后端 未结 22 2950
面向向阳花
面向向阳花 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:40

    static int[] sort(int[] arr){
            int idx = 0;
            int len = arr.length - 1;
            int counter = len;
            while(true){
                if(idx != len && arr[idx] > arr[idx+1]){
                    swap(arr, idx, idx + 1);
                    counter--;
                }
                idx++;
                if(counter == len && idx == len){
                    break;
                }
                if(idx == len){
                    idx = 0;
                    counter = len;
                }
            }
            return arr;
        }
    
    
        void swap(int[] arr, int i, int j) {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    

提交回复
热议问题