java:根据数组2对数组1进行排序

发布于 2024-11-04 23:37:54 字数 1102 浏览 1 评论 0原文

感谢 Zirak 在我的 上一篇文章我在JavaScript中实现了以下内容:

var arr1 =[0,1,2,3];
var arr2 =["ac", "bc", "ad", "e"];
var result = arr1 .sort(function(i, j){return arr2[i].localeCompare(arr2[j])})
document.write(result );

在JavaScript中实现这一点的方法非常紧凑,Java实现也可以如此简单地实现吗?我只能想到实现 Comparable 接口,如下所示:

public class testCompare {
    public static String[] arr2={"ac", "bc", "ad", "e"};
    public static Obj[] arr1={new Obj(0), new Obj(1), new Obj(2), new Obj(3)};
    static class Obj implements Comparable{
            int index=0;
            public Obj(int i){
                    index=i;
            }
            @Override
            public int compareTo(Object o) {
                    return arr2[index].compareTo(arr2[((Obj)o).index]);
            }
     }
}

但是如果数组有 X 个项目,那么我将不得不创建 X 个 Objs,是否有另一种方法可以更简单地实现此目的?另一个问题是,如果我执行上述方法,在java和JavaScript中排序的时间复杂度是多少,它们都是O(n^2)吗?多谢

Thanks for the help from Zirak In my previous post i implemented the following in JavaScript:

var arr1 =[0,1,2,3];
var arr2 =["ac", "bc", "ad", "e"];
var result = arr1 .sort(function(i, j){return arr2[i].localeCompare(arr2[j])})
document.write(result );

The way to achieve this is quite compact in JavaScript, can a java implementation of this be also achieved by such simplicity? I could only think of implementing the Comparable interface like the following:

public class testCompare {
    public static String[] arr2={"ac", "bc", "ad", "e"};
    public static Obj[] arr1={new Obj(0), new Obj(1), new Obj(2), new Obj(3)};
    static class Obj implements Comparable{
            int index=0;
            public Obj(int i){
                    index=i;
            }
            @Override
            public int compareTo(Object o) {
                    return arr2[index].compareTo(arr2[((Obj)o).index]);
            }
     }
}

but if the array have X many items, then I will have to create X many Objs, is there another way that I could achieve this more simply? Another question is, if I do the above method what would be the time complexity for the sorting both in java and in JavaScript, are they all O(n^2)? Thanks a lot

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

○闲身 2024-11-11 23:37:54
public class MyComparator implements Comparator<Integer> {
    @Override
    public int compare(Integer i1, Integer i2) {
        return arr2[i1.intValue()].compareTo(arr2[i2.intValue()]);
    }
}

Arrays.sort(arr1, new MyComparator());

这相当于 JavaScript 排序。 Comparator 对象用作 JavaScript 中的回调函数。

public class MyComparator implements Comparator<Integer> {
    @Override
    public int compare(Integer i1, Integer i2) {
        return arr2[i1.intValue()].compareTo(arr2[i2.intValue()]);
    }
}

Arrays.sort(arr1, new MyComparator());

This is the equivalent of the JavaScript sort. The Comparator object is used as the callback function is used in JavaScript.

脱离于你 2024-11-11 23:37:54

尝试使用 TreeMap (假设您想对整数进行排序),这意味着所有条目均按其字符串键排序:

SortedMap<String, Integer> map = new TreeMap<String, Integer>();
map.put("ac", 0);
map.put("bc", 1);
map.put("ad", 2);
map.put("e", 3);

for( Map.Entry<String, Integer> entry : map.entrySet() )
{
  System.out.println(entry.getKey() + " - " + entry.getValue());
}

输出:

ac - 0
ad - 2
bc - 1
e - 3

对数组进行排序并获取先前索引的新顺序您可以迭代数组并将索引作为 Integer 对象添加到映射中:

String[] input = {"ab", "bc", "ad" , "e" };
SortedMap<String, Integer> map = new TreeMap<String, Integer>();
for( int i = 0; i < input.length; ++i )
{
  map.put(input[i], i); //or use values from another array, e.g. map.put(inputKeys[i], inputValues[i]);
}

如果您需要按自然顺序以外的任何其他方式对键进行排序,您可以将 Comparator 添加到TreeMap 构造函数。

Try using a TreeMap<String, Integer> (assuming you want to sort integers) which means all entries are sorted by their string key:

SortedMap<String, Integer> map = new TreeMap<String, Integer>();
map.put("ac", 0);
map.put("bc", 1);
map.put("ad", 2);
map.put("e", 3);

for( Map.Entry<String, Integer> entry : map.entrySet() )
{
  System.out.println(entry.getKey() + " - " + entry.getValue());
}

Output:

ac - 0
ad - 2
bc - 1
e - 3

To sort an array and get the new order of the previous indices you could iterate over the array and add the indices as Integer objects to the map:

String[] input = {"ab", "bc", "ad" , "e" };
SortedMap<String, Integer> map = new TreeMap<String, Integer>();
for( int i = 0; i < input.length; ++i )
{
  map.put(input[i], i); //or use values from another array, e.g. map.put(inputKeys[i], inputValues[i]);
}

If you need to sort the keys by anything else but the natural order, you can add a Comparator<String> to the TreeMap constructor.

陌若浮生 2024-11-11 23:37:54
public class SortA1byA2array 
{
public static void main (String[] args) 
{
int[] arr1={2,1,2,5,7,1,9,8,3,6,8,8};       
int[] arr2={2,1,8,3};   
TreeMap hm=new TreeMap();   
int count=1;
        for(int i=0;i<arr1.length;i++){
            if(hm.containsKey(arr1[i])){
                hm.put(arr1[i], ++count);
            }
            else{
                count=1;
                hm.put(arr1[i],count);
            }
        }


        for(int i=0;i<arr2.length;i++){
            if(hm.containsKey(arr2[i])){
                for(int j=0;j<(Integer)hm.get(arr2[i]);j++){
                    System.out.println(arr2[i]);
                }
                hm.remove(arr2[i]);
            }
        }

         Iterator it = hm.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry pairs = (Map.Entry)it.next();
                System.out.println(pairs.getKey());
                it.remove(); 
            }
    }
}
public class SortA1byA2array 
{
public static void main (String[] args) 
{
int[] arr1={2,1,2,5,7,1,9,8,3,6,8,8};       
int[] arr2={2,1,8,3};   
TreeMap hm=new TreeMap();   
int count=1;
        for(int i=0;i<arr1.length;i++){
            if(hm.containsKey(arr1[i])){
                hm.put(arr1[i], ++count);
            }
            else{
                count=1;
                hm.put(arr1[i],count);
            }
        }


        for(int i=0;i<arr2.length;i++){
            if(hm.containsKey(arr2[i])){
                for(int j=0;j<(Integer)hm.get(arr2[i]);j++){
                    System.out.println(arr2[i]);
                }
                hm.remove(arr2[i]);
            }
        }

         Iterator it = hm.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry pairs = (Map.Entry)it.next();
                System.out.println(pairs.getKey());
                it.remove(); 
            }
    }
}
找回味觉 2024-11-11 23:37:54

回答你问题的第二部分:Java中的Arrays.sort保证了O(n log n)时间复杂度,如指定的API< /a>.

In response to the second part of you question: Arrays.sort in Java has guaranteed O(n log n) time complexity, as specified in the API.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文