【一次过】【2017美丽联合】特殊交换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/89160732

现有一个n个整数的序列,你要做的就是交换两个数的位置直到整个序列按照升序排列,那么将这个整数序列排好序,需要交换多少次?例如,1,2,3,5,4,我们只需要交换一次,即将5和4交换即可。

输入描述:

第一行输入一个正整数n(n≤1000),表示数字序列的元素个数,占一行;接下来一行输入从1到n的n个整数排序,中间用空格隔开

输出描述:

输出序列升序排列需要的最少交换次数

输入例子1:

4
4 3 2 1

输出例子1:

6

解题思路:

冒泡排序的应用。

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int n = sc.nextInt();
            int[] nums = new int[n];
            for(int i=0; i<n; i++)
                nums[i] = sc.nextInt();
            
            System.out.println(helper(nums));
        }
    }
    
    public static int helper(int[] nums){
        int res = 0;
        
        for(int i=0; i<nums.length; i++){
            for(int j=0; j<nums.length-i-1; j++){
                if(nums[j] > nums[j+1]){
                    swap(nums, j, j+1);
                    res++;
                }
            }
        }
        
        return res;
    }
    
    public static void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/89160732