get indexes of n smallest elements in an array

前端 未结 6 1591
醉酒成梦
醉酒成梦 2020-12-17 08:15

I have an int array int[] myArray = new int[100]; and want to get indexes of smallest 10 (any n) elements. How can I do this?

6条回答
  •  隐瞒了意图╮
    2020-12-17 08:39

    make an object that contains the number and the index, then make an array of these objects, then perform Array.Sort(arrayset[], comparator) java docs. Then you can just pick out the top x items from the sorted array.

    EDIT: Something like this... [I had used this to sort according to 'distance'

    import java.util.Arrays;
    import java.util.Comparator;
    
    public class NearestObject
    {
        public NearestObject(int position, int distance)
        {
             this.Position = position;
             this.Distance = distance;
        }
        public int Position = 0;
        public int Distance = 0;
    
        public static NearestObject[] SortDistance(NearestObject[] items)
        {
            Arrays.sort(items, new DistanceSort());
            return items;
        }
    
    }
    
    class DistanceSort implements Comparator
    {
        public int compare(NearestObject o1, NearestObject o2)
        {
            return o1.Distance - o2.Distance;
        }
    }
    

提交回复
热议问题