给定2个数组,如何按升序对第一个数组进行排序,并交换第二个数组值以匹配第一个数组?

时间:2014-12-09 18:33:26

标签: java arrays sorting

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 [])            8 13 15 10 12 16 16 9(适用于ft [])

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

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

1 个答案:

答案 0 :(得分:0)

更改此

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;
}