Minimum Swaps 2

  • + 0 comments

    I though might be helpfull to someone..

    int minimumSwaps(int arr_count, int* arr) {
    
        int index = 0;
        int swaps = 0;
        int elem = 0;
        int tmp = 0;
    
        while (true)
        {
            elem = arr[index];
            if (elem != index +1) 
            {
                tmp = arr[index];
                arr[index] = arr[elem - 1];
                arr[elem - 1] = tmp;
                swaps++;
            }
            if (index + 1 == arr[index])
            {
                // move on to the next element
                index++;
            }
            if (arr_count == index + 1)
            {
                // we are done
                break;
            }
        }
        return swaps;
    }