Running Time of Algorithms

  • + 0 comments

    My answer in Typescript, simple

    function insertionSort1(arr: number[]): [number[], number] {
        let i = arr.length - 1
        let x = arr[i]
        let s = 0
    
        while (x != 0) {
            let t = arr[i - 1] ?? 0
            if (t < x) {
                arr[i] = x
                x = 0
            } else {
                arr[i] = arr[i - 1]
                i--
                s++
                if (t == x) s--
            }
        }
    
        return [arr, s]
    }
    
    const arrayCompare = <T>(arr1: T[], arr2: T[]): boolean => {
        if (arr1.length != arr2.length) return false;
        return arr1.every((e, i) => e == arr2[i])
    }
    
    function runningTime(arr: number[]): number {
        /**
         * with small changes from previos answer, counting swaping attemp and sum em all
         */
    
        let swap_counter = 0
    
        for (let i = 1; i < arr.length; i++) {
            let [sorted_part, swaped] = insertionSort1(arr.slice(0, i + 1))
            let arr_sorted = [...sorted_part, ...arr.slice(i + 1)]
    
            if (!arrayCompare(arr, arr_sorted)) {
                arr = arr_sorted
                swap_counter += swaped
            }
        }
    
        return swap_counter;
    }