Running Time of Algorithms

  • + 0 comments

    Here is my solution with Java 8:

        public static int runningTime(List<Integer> arr) {
        int counter=0;
        
        //convert arraylist arr to array 
        Integer[] array = new Integer[arr.size()]; 
        arr.toArray(array);
        
        //sorting the array 
        for(int i = 1; i < array.length; i++){
                int a = array[i];
                int j = i - 1;
                while(j >= 0 && array[j] > a){
                    array[j + 1] = array[j];
                    //add value to counter in each iteration
                    counter=counter+1;
                    j--;                
                }
                array[j + 1] = a;
            }
            return counter;
        }