【问题标题】:Given 2 arrays, how to sort the first array in ascending order, and swap the second array values so as to match with the first array?给定2个数组,如何对第一个数组进行升序排序,并交换第二个数组的值以匹配第一个数组?
【发布时间】:2014-12-09 18:33:26
【问题描述】:
import java.util.Scanner;

public class Sort
{
    public static void main(String[] args)
    {
        int[] at = new int[8];
        int[] ft = new int[8];
        int temp = 0 ,temp1 = 0;

        Scanner s = new Scanner(System.in);
        System.out.println("Enter values for first array");
        for(int a = 0;a<8;a++)
        {
            at[a] = s.nextInt();

        }   
        System.out.println("Enter values for second  array");
        for(int a = 0;a<8;a++)
        {
            ft[a] = s.nextInt();

        }   

        for(int i = 0;i<at.length;i++)
        {

            for(int j = at.length-1; j>i; j--)
            {
                if(at[j]<at[j-1])
                {
                    temp = at[j];
                    at[j] = at[j-1];
                    at[j-1] = temp;

                    temp1 = ft[j];
                    ft[j] = ft[j - 1];
                    ft[j-1] = temp1;
                }
            }
        }

        for(int ab : at)
            System.out.print(ab+" ");
        System.out.println();
        System.out.println("---------------------------");
        for(int ab : ft)
            System.out.print(ab+" ");
    }
}

输入为:6 11 7 7 10 14 13 8(for at[]) 8 13 15 10 12 16 16 9(对于 ft[])

输出为:6 7 7 8 10 11 13 14(对于 at[]) 8 15 10 9 12 13 16 16(对于 ft[])

我改变了第二个数组的交换,即 temp1 = ft[j],ft[j] = ft[j-1],ft[j-1] =temp1

【问题讨论】:

    标签: java arrays sorting


    【解决方案1】:

    改变这个

    if(at[j]<at[j-1])
    {
        temp = at[j];
        at[j] = at[j-1];
        at[j-1] = temp;
    
        temp1 = ft[j]; // <-- here, and ft[j].
        ft[j] = ft[j - 1];
        ft[j] = temp1;
    }
    

    【讨论】:

    • 预期输出是什么?为什么?
    • 你几乎正确,但你需要写 ft[j] = ft[j-1]。这给出了正确的答案
    • 输出我已经提到它,在问题本身下面
    • @KNS 已编辑,我没有注意到。好电话。
    猜你喜欢
    • 1970-01-01
    • 2016-11-05
    • 2018-11-18
    • 2020-11-19
    • 2020-08-01
    • 2021-12-01
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多