Minimum Swap Required to Sort an Array Starts with 1, Jumbled, No Duplicate, Nothing Missing

package org.wesome.dsalgo;

import java.util.Arrays;

public class MinSwap {
    public static int minSwap(int[] arr) {
        int indx = 0;
        int minSwap = 0;
        int temp;
        int arrLen = arr.length;
        while (indx < arrLen) {
            if (arr[indx] != indx + 1) {
                temp = arr[indx];
                arr[indx] = arr[temp - 1];
                arr[temp - 1] = temp;
                minSwap++;
            } else {
                indx++;
            }
        }
        System.out.println(minSwap + " swap is required to sort array = " + Arrays.toString(arr));
        return minSwap;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class MinSwapTest {
    @Test
    void minSwap1() {
        int[] arr = new int[]{1, 2, 4, 3};
        int minSwap = MinSwap.minSwap(arr);
        Assertions.assertEquals(1, minSwap);
    }

    @Test
    void minSwap2() {
        int[] arr = new int[]{4, 3, 2, 1};
        int minSwap = MinSwap.minSwap(arr);
        Assertions.assertEquals(2, minSwap);
    }
}
plugins {
    id 'java'
}

group 'org.wesome'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
}

test {
    useJUnitPlatform()
}

 

follow us on