在java中用索引对算法排序

时间:2018-08-08 07:39:32

标签: java sorting

我有一组用于srting算法的值。我已经成功地整理了它们。但是我也想对排序后的每个元素都有索引。例如:

sel_list = [{'a': 0}, {'a': 4}, {'a': 4}, {'b': 8}, {'b': 9}, {'d': 9}]
result_dict = {}
for item in sel_list:
    key = list(item.keys())[0]
    if key in result_dict:
        if item[key] > result_dict[key][key]:
            result_dict.update({key: item})
    else:
        result_dict.update({key: item})
result_list = [v for k, v in result_dict.items()]
print(result_list)

我使用以下逻辑进行排序。但无法获取索引

Array = [95, 53, 24, 10]
Output after sorting should be like :
10 at index 3, 24 at index 2, 53 at index 1 and 95 at index 0

6 个答案:

答案 0 :(得分:4)

由于这可能是家庭作业,因此请注意以下几点:

  • 在排序之前,为您的初始数组创建一个副本
  • 排序后,迭代原始数组,然后查找 sorted 数组中的每个值的索引,并打印
  • 棘手的部分是处理反复出现的值。但这取决于您的确切要求。

或者,您可以考虑引入一种有用的数据结构,例如Pair<Integer, Integer>类。第一个条目代表值,第二个条目代表索引。然后,您可以在该类上定义自己的“排序”。

答案 1 :(得分:2)

如先前所建议,我还建议使用其他Item类,该类存储要在其上排序的项目和初始索引:

public class Item<T extends Comparable<T>> implements Comparable<Item<T>> {
    public final T item;
    public final int index;

    public Item(T item, int index) {
        if (item == null)
            throw new NullPointerException("the given item is null!");
        this.item = item;
        this.index = index;
    }

    @Override
    public int compareTo(Item<T> t) {
        if (t == null)
            return 1;
        return item.compareTo(t.item);
    }
}

当需要对双精度数组进行排序时,请首先创建一个包含ArrayList的{​​{1}},其中Items存储输入数组的双精度数组和初始索引。由于Item类实现了Comparable接口,因此您可以使用Collections.sort进行排序(这比您的bubbleort实现要快):

public static void sort(Integer... array) {
    List<Item<Integer>> copy = new ArrayList<Item<Integer>>(array.length);

    // copy the input array
    for (int i = 0; i < array.length; ++i)
        copy.add(new Item<Integer>(array[i], i));


    Collections.sort(copy);

    for (Item<Integer> t : copy)
        System.out.println(t.item + " at index " + t.index);
}

答案 2 :(得分:0)

尝试一下:

  1. 创建一个Pair类,例如

class Pair { int val; int index; }

  1. valuez

  2. 进行排序
  3. index将保留初始索引

答案 3 :(得分:0)

我刚刚尝试了以下方法,但效果很好。

int[] index = {0,1,2,3}
for (int p=0;p<((list.size())-1);p++) 
                 {
                     int min = p;

                     count++;
                     for(int q=p+1; q<list.size();q++) 
                     {
                        if(doubleArray[q]< doubleArray[min])
                        {
                            min = q;
                        }
                     }
                     double smallNumber = doubleArray[p];
                     doubleArray[p] = doubleArray[min];
                     doubleArray[min] = smallNumber;

                     store = index[p];
                     index[p] = index[min];
                     index[min] = store;

                 }
}

成功了。这也是正确的做法吗?我是Java新手。我处于一个非常基础的阶段。

答案 4 :(得分:0)

我建议采用以下方法:

    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.SortedSet;
    import java.util.TreeSet;

    public class trial
    {
     public static void main(String[] args)
     {
    List<Integer> aList = Arrays.asList(95, 53, 24, 10);
    Map<Integer, Integer> aMap = new HashMap<>();

    int index = 0;
    for( Integer aInteger : aList )
    {
      aMap.put(aInteger, index);
      index++;
    }

    SortedSet<Integer> keys = new TreeSet<>(aMap.keySet());

    for( Integer key : keys )
    {
      Integer value = aMap.get(key);
      System.out.println(key + " at index " + value);
     }
    }
    }

答案 5 :(得分:0)

在这里找到旧索引和短值

Map<Integer, Integer> map1 = numbers.stream().collect(Collectors.toMap(i -> i, i -> numbers.indexOf(i))).           entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));

//输出{10 = 3,24 = 2,53 = 1,95 = 0}