简体   繁体   中英

Custom Sorting Algorithm in Java?

Hey guys so I want to write a small Java Program that helps me sort a list. Imagine the list looks like this: Apples, Grapefruit, Bananas, Pineapples, Coconuts

Now I don't want to sort alphabetically or anything like that but for example by what fruit I like the most, so the sorted list could look like this: Coconuts, Bananas, Apples, Pineapples, Grapefruit

My idea so far was that it could kinda go like that: Apples is written into the list. Then Grapefruit and apple is compared and the user says what he likes more (here Apples) so Grapefruits move under Apples. Then it compares Bananas with eg Apples and the user tells the program he likes Bananas more so it goes above Apples and doesnt have to compare with Grapefruit anymore which saves a lot of time. The Program should handle a few hundred entries and comparisions in the end so saving time by asking fewer questions will save a lot of time. Am I on the right track? Also what would be the best way to input the list, an array, an arraylist, or...?

How should this be implemented? Is there a fitting sorting Algorithm? Thanks in advance!

The simplest way is to use Collections.sort with a custom comparator that asks for user input.

Scanner sc = new Scanner(System.in);
Collections.sort(fruits, (a, b) -> {
    System.out.println("Do you prefer " + a + " or " + b + "?");
    String preference = sc.next();
    return preference.equals(a) ? -1 : preference.equals(b) ? 1 : 0;
});

You should build a Binary Search Tree.

As you're inserting new fruits, you ask the user which they like best, to find where to insert the new fruit node. To keep the number of questions down, keep the tree Balanced.

Once the "preference tree" has been built, you can iterate the tree depth-first, assigning incremental "preference values" to each fruit, and build a Map<String, Integer> , so you can quickly lookup any fruits preference values, aka sort sequence number.

The accepted answer is fine, but consider also this alternative:

You could store the fruits in a max-heap, which can be done with an ArrayList (when you don't know the number of fruits beforehand) or a plain array.

When you insert a new fruit, it is appended at the end of the array, and as you let it sift up (according to the heap algorithm), you ask the user for the result of the comparison(s), until the fruit is considered less liked than the one compared with (or it becomes the root -- at index 0).

As post processing, you need to pull out all elements from the top of the heap, again using the appropriate heap algorithm. They will come out in sorted order.

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