Running Time of Algorithms

Sort by

recency

|

270 Discussions

|

  • + 0 comments

    Here is my c++ solution, you can watch the explanation here : https://youtu.be/pAWOIEQemtc

    int runningTime(vector<int> arr) {
        int i,j;
        int value;
        int result = 0;
        for(i=1;i<arr.size();i++)
        {
            value=arr[i];
            j=i-1;
            while(j>=0 && value<arr[j])
            {
                arr[j+1]=arr[j];
                j=j-1;
                result ++;
            }
            arr[j+1]=value;
        }
        return result;
    }
    
  • + 0 comments

    java8

        public static int runningTime(List<Integer> arr) {
            int shiftCounter = 0;
            for (int i=1; i < arr.size(); i++) {
                for (int j=0; j < i; j++) {
                    if (arr.get(i) < arr.get(j)) {
                        int toInsert = arr.remove(i);
                        arr.add(j, toInsert);
                        shiftCounter += i-j;
                    }
                }
            }
            return shiftCounter;
        }
    
  • + 0 comments

    My C code 😎😁

    int runningTime(int arr_count, int* arr) {
        int nbrOperation = 0;
        for(int i = 1;i < arr_count; i++){
            int cle = arr[i];
            int j = i - 1;
            
            while(j >= 0 && arr[j] > cle){
                arr[j + 1] = arr[j];
                j--;
                nbrOperation++;
            }
            arr[j + 1] = cle;
        }
        return nbrOperation;
    }
    
  • + 0 comments
    def runningTime(arr):
        shifts = 0
        for i in range(1,len(arr)):
            j = i
            while j >= 1 and arr[j] < arr[j-1]:
                shifts += 1
                arr[j], arr[j-1] = arr[j-1], arr[j]
                j -= 1
    
        return shifts
    
  • + 0 comments

    Python3

    ` def runningTime(arr): shifts = 0 for i in range(1,len(arr)): j = i while j >= 1 and arr[j] < arr[j-1]: shifts += 1 arr[j], arr[j-1] = arr[j-1], arr[j] j -= 1

    return shifts
    

    `