日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

java对数组进行排序_用Java对数组进行排序所需的最少交换

發布時間:2025/3/11 java 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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对数组进行排序所需的最少交换的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。