How to sort an array in a single loop?

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

    This can be used to sort array usinga single loop:- Points to be noed:

    1. updating the value of i to -1 so that it alwasy starts from 0 after i++
    2. reducing the length(size--) of array as maximum valued element ends up at the end for every time the loop completes

    Code:

    void sort(int *arr,int size){
        int i;
        for (i = 0; i arr[i+1]){
                arr[i]=arr[i]+arr[i+1];
                arr[i+1]=arr[i]-arr[i+1];
                arr[i]=arr[i]-arr[i+1];
                if(i==size-2){
                    printf("%s\n","inside if loop" );
                    i=-1;
                    size--;
                }
            }
        }
    }
    

提交回复
热议问题