Answers for "min swaps to sort array"

0

minimum swaps to sort an array

import java.io.*;
import java.math.*;
import java.util.*;

public class Swap {
	static int minimumSwaps(int[] arr) {
		int swap=0;
		boolean visited[]=new boolean[arr.length];

		for(int i=0;i<arr.length;i++){
			int j=i,cycle=0;

			while(!visited[j]){
				visited[j]=true;
				j=arr[j]-1;
				cycle++;
			}
			
			if(cycle!=0)
				swap+=cycle-1;
		}
		return swap;
	}

	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		int[] arr = new int[n];
		
		for (int i = 0; i < n; i++) {
			arr[i] = scanner.nextInt();
		}
		
		int res = minimumSwaps(arr);
		System.out.println(res);
		scanner.close();
	}
}
Posted by: Guest on July-17-2020
-1

minimum number of swaps to sort an array javascript

function minimumSwaps(arr) {
    let swap = 0
    for(let i = 0;i<arr.length;i++) {
        while(arr[i] !== i+1) {
            let temp = arr[i]
            arr[i] = arr[temp - 1]
            arr[temp - 1] = temp
            swap++; 
        }
    }
    return swap

}
Posted by: Guest on January-21-2021
0

minimum swaps to sort an array

import java.io.*;
import java.math.*;
import java.util.*;

public class Swap {
	static int minimumSwaps(int[] arr) {
		int swap=0;
		boolean visited[]=new boolean[arr.length];

		for(int i=0;i<arr.length;i++){
			int j=i,cycle=0;

			while(!visited[j]){
				visited[j]=true;
				j=arr[j]-1;
				cycle++;
			}
			
			if(cycle!=0)
				swap+=cycle-1;
		}
		return swap;
	}

	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		int[] arr = new int[n];
		
		for (int i = 0; i < n; i++) {
			arr[i] = scanner.nextInt();
		}
		
		int res = minimumSwaps(arr);
		System.out.println(res);
		scanner.close();
	}
}
Posted by: Guest on July-17-2020
-1

minimum number of swaps to sort an array javascript

function minimumSwaps(arr) {
    let swap = 0
    for(let i = 0;i<arr.length;i++) {
        while(arr[i] !== i+1) {
            let temp = arr[i]
            arr[i] = arr[temp - 1]
            arr[temp - 1] = temp
            swap++; 
        }
    }
    return swap

}
Posted by: Guest on January-21-2021

Code answers related to "min swaps to sort array"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language