Algorithm to rotate an array in linear time

后端 未结 22 2097
我寻月下人不归
我寻月下人不归 2020-11-28 05:05

How to rotate an integer array by i times using swap function only in linear time.

22条回答
  •  北海茫月
    2020-11-28 05:43

    Here's a small snippet thats works in O(n), written in JavaScript. The keyconcept is, that you always have to work with the replaced item.

    function swap(arr, a, v) {
        var old = arr[a];
        arr[a] = v;
        return old;
    }
    
    function rotate(arr, n) {
        var length = arr.length;
        n = n % length;
        if(!n) return arr;
    
        for(var cnt = 0, 
                index = 0,
                value = arr[index],
                startIndex = index; 
            cnt < length; 
            cnt++) {
    
            // Calc next index
            var nextIndex = mapIndex(index, n, length);
    
            // Swap value with next
            value = swap(arr, nextIndex, value)
    
            if(nextIndex == startIndex) {
                startIndex = index = mapIndex(index, 1, length);
                value = arr[index];
            } else {
                index = nextIndex;
            }
        }
    
        return arr;
    }
    
    function mapIndex(index, n, length) {
        return (index - n + length) % length;
    }
    
    console.log(rotate([1,2,3,4,5,6,7,8,9], 5))
    console.log(rotate([1,2,3,4,5,6], 2))
    

提交回复
热议问题