简体   繁体   English

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

[英]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?

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+" ");
    }
}

Input is : 6 11 7 7 10 14 13 8(for at[]) 8 13 15 10 12 16 16 9(for ft[]) 输入为:6 11 7 7 10 14 13 8(用于at [])8 13 15 10 12 12 16 16 9(用于f​​t [])

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

I've changed swapping of second array ie temp1 = ft[j],ft[j] = ft[j-1],ft[j-1] =temp1 我已经更改了第二个数组的交换,即temp1 = ft [j],ft [j] = ft [j-1],ft [j-1] = temp1

Change this 改变这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM