java对数组进行排序
Problem:
问题:
In this problem, we would have an unordered array with consecutive distinct natural numbers [1,2,3,..n], where n is the size of the array. We have to find the minimum number of swaps required to sort the array in ascending order.
在此问题中,我们将拥有一个具有连续的不同自然数[1,2,3,.. n]的无序数组,其中n是数组的大小。 我们必须找到按升序对数组进行排序所需的最小交换次数 。
Note: Think and try by yourself before looking to the solution...
注意:在寻求解决方案之前,请自己思考并尝试...
Solution:
解:
This problem can be solved easily by observing the actual position of elements and their current position , the actual position of element in sorted array will be the a[cur]-1 (element-1), by tracking the actual position of element if we come back to the current element then there exist a cycle , then count the size of that cycle , the number of swaps will be cycling size-1, do this for all the cycles and add them together.
通过观察元素的实际位置及其当前位置,可以很容易地解决此问题,如果我们跟踪元素的实际位置,则排序数组中元素的实际位置将为a [cur -1 ] ( element-1 )回到当前元素,然后存在一个循环,然后计算该循环的大小 ,交换次数将为循环size-1 ,对所有循环进行此操作并将它们加在一起。
Example:
例:
Let an array: A =[2, 4, 5, 1, 3]
设一个数组:A = [2,4,5,1,3]
There exist two cycles:
Cycle 1: 2 → 4 → 1 → 2
Cycle 2: 5 → 3 → 5
存在两个周期:
周期1:2→4→1→2
周期2:5→3→5
Size of cycle = number of nodes:
Size of cycle 1=3
Size of cycle 2=2
周期大小=节点数:
周期1的大小= 3
周期2 = 2
Number of swaps: (3-1)+(2-1) = 3
掉期数量: (3-1)+(2-1)= 3
Program:
程序:
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();
}
}
Output
输出量
4
4 3 2 1
2
翻译自: https://www.includehelp.com/java-programs/minimum-swaps-required-to-sort-an-array.aspx
java对数组进行排序