简体   繁体   中英

Sort array in a specific order in java

I am trying to sort an array to a specific order. So for example, I have this array

{6,1,1,5,6,1,5,4,6}

and I want them to be sorted to this order

{4,1,6,5}

expected new array would be

 {4,1,1,1,6,6,6,6,5}

My idea is this,

public class Sort {

    static int[] list = { 6, 1, 1, 5, 6, 1, 6, 4, 6 };
    static int[] sorted = { 4, 1, 6, 5 };
    static int[] newList = new int[list.length];
    static int count = 0;

    public static void main(String[] args) {
        for (int i = 0; i < sorted.length; i++) {
            for (int j = 0; j < list.length; j++) {

                if (list[j] != sorted[i])
                    continue;
                else
                    newList[count++] = sorted[i];

            }
        }
    }
}

It works fine, however, I am not sure if this is the fastest and easier way to do this regarding speed and memory cause the list could have too many numbers.

You can use java built-in sort algorithm with a customized comparator.

public static void main(String[] args) {

    Integer[] list = { 6, 1, 1, 5, 6, 1, 6, 4, 6 };
    int[] sorted = { 4, 1, 6, 5 };

    Map<Integer, Integer> order = new HashMap<>();
    for (int i = 0; i < sorted.length; i++)
        order.put(sorted[i], i);

    Arrays.sort(list, (a ,b) -> order.get(a) - order.get(b));

    System.out.println(Arrays.toString(list));
}

The output is [4, 1, 1, 1, 6, 6, 6, 6, 5] .

If you

  • know the possible elements in advance
  • and they are relatively small numbers

you can simply count them:

int stats[]=new int[7]; // "largest possible element"+1
for(int i=0;i<list.length;i++)
  stats[list[i]]++;

and then reconstruct the ordered list:

int idx=0;
for(int i=0;i<sorted.length;i++){
  int val=sorted[i];
  for(int j=stats[val];j>0;j--)
    newlist[idx++]=val;

The two snippets in total have "2*list.length" steps, which is probably faster than your original "sorted.length*list.length" loop-pair.
As you have not described the actual use-case, it is hard to tell more. For example if you have these numbers only, you probably do not need the ordered result to be an actual list. However if these numbers are just part of an object, this build-a-statistics approach is not applicable.

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