简体   繁体   中英

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[])

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

I've changed swapping of second array ie 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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