Minimum Swaps 2

  • + 0 comments

    My JavaScript (JS/node.js) solution. This assumes the first number may not start at 1.

    // Complete the minimumSwaps function below.
    function minimumSwaps(arr) {
        let swaps = 0; // Counter for minimum number of swaps
        // bubble sort
        
        let index = 0;
        
        // Find the lowest value in the array:
        const minimum = Math.min(...arr);
    
        while (index < arr.length) {
            // Subtract 1 from the element to determin it's correct position in the array
            const elementAsIndex = arr[index] - 1;
            // Because the numbers are consecutive, but may not start at 1,
            // we can determin what the correct number is for our current index by...
            // adding the minimum value and adding the index. We subtract 1 to get the position.
            const locationInArray = index + minimum - 1;
    
    
            // Check if element is greater or less than it's position in the array
            if(elementAsIndex !== locationInArray) {
                swaps += 1;
                // Swap the elements
                [ arr[elementAsIndex], arr[locationInArray] ] = [ arr[locationInArray], arr[elementAsIndex] ];
            } else {
                index += 1;
            }   
        }
        // key element is consecutive... does it always start at 1?
        
        return swaps;
    
    }