java对数组进行排序_用Java对数组进行排序所需的最少交换
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
.minHeight{min-height: 250px;}@media (min-width: 1025px){.minHeight{min-height: 90px;}} .minHeight{min-height: 250px;}@media (min-width: 1025px){.minHeight{min-height: 90px;}}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
輸出量
44 3 2 12翻譯自: https://www.includehelp.com/java-programs/minimum-swaps-required-to-sort-an-array.aspx
java對數組進行排序
總結
以上是生活随笔為你收集整理的java对数组进行排序_用Java对数组进行排序所需的最少交换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在Ruby中使用&运算符(new_arr
- 下一篇: 如何在Java中对Collection对