排序并行数组 [英] Sorting Parallel Arrays

查看:55
本文介绍了排序并行数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java入门者,使用一本旧教科书和 Head First:Java 书来弄清楚一些东西.

Beginner in Java using an old textbook and Head First: Java books to figure some stuff out.

我有三个并行的数组.我需要能够根据用户选择按标题,作者或页面数进行排序.我可以使用 Arrays.sort()对一个数组进行排序,但是我迷上了如何对其他两个数组进行排序以与新排序的数组相对应.

I have three arrays all parallel. I need to be able to sort by Title, Author, or Page Count based on user selection. I can sort one using Arrays.sort() but I'm getting hung up on how to sort the other two arrays to correspond to the new sorted one.

说我对 BookTitle 数组进行排序,但是我将需要显示其相应数组的正确作者和页数,这让我很困惑.

Say I sort the BookTitle array, but I'm going to need to display the proper author and page count of its respective arrays and I'm stumped.

do
{
    entry = JOptionPane.showInputDialog(null,
                                        "Enter your sort preference: \n" +
                                        "T = Sort by TITLE\n" +
                                        "A = Sort by AUTHOR\n" +
                                        "P = Sort by PAGE Count");

    c = entry.charAt(0);

    switch (c)
    {
    case 't':
    case 'T':
        Arrays.sort(BookTitle);
        for (int x = 0; x < BookTitle.length; x++)
        {
            msg += ("Title: " + BookTitle[x] + "\n");
        }
        JOptionPane.showMessageDialog(null, msg);
        isValid = true;
        break;

    case 'a':
    case 'A':
        isValid = true;
        break;

    case 'p':
    case 'P':
        isValid = true;
        break;

    default:
        JOptionPane.showMessageDialog(null, "Invalid entry");
        break;
    }
} while (isValid == false);

推荐答案

public class SortUtils {
    public static void sort(long[] x, long[] y) {
        for (int i = 0; i < x.length; i++) {
            for (int j = i; j > 0 && x[j - 1] > x[j]; j--) {
                swap(x, j, j - 1);
                swap(y, j, j - 1);
            }
        }
    }

    private static void swap(long anArray[], int a, int b) {
        long t = anArray[a];
        anArray[a] = anArray[b];
        anArray[b] = t;
    }
}

这篇关于排序并行数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆