Java Set Framework algorithm __java

Source: Internet
Author: User
Tags shuffle sorts

The polymorphic algorithm described here is part of the reusable functionality provided by the Java platform. They all come from collection classes, all in the form of static methods, with the first argument being a collection of actions to take. Most of the algorithms provided by the Java platform operate on a list instance, but some of these algorithms operate on any set instance. This section briefly describes the following algorithms: Sort shuffle (scrambled order) general data Operations Search composition Find Extreme order

The sort algorithm reorder a list so that its elements are sorted in ascending order. Provides two types of operations. This simple form is sorted according to the natural sort of elements. If you are unfamiliar with the concept of natural sorting, please read the object ordering section.

The sort operation uses a slightly optimized merge sorting algorithm, which is fast and stable:

Fast: It's guaranteed to run at N log (n) times and run faster on almost sorted lists. Empirical testing shows that it is as fast as a highly optimized fast sort. Fast sorting is often considered to be faster than merge sorting, but is unstable and does not guarantee Nlog (n) performance.
Stability: It does not rearrange equal elements. This is important if you are repeatedly sorting the same list on different properties. If a user of a mail program sorts the Inbox by sending a date, and then sorts it through the sender, the user will naturally expect the list of messages in the given sender (still) to be sorted by message date. Only when the second condition is stable is there a guarantee.
The following applet prints its arguments in a dictionary (alphabetical) order.

Import java.util.*;

public class Sort {public
    static void Main (string[] args) {
        list<string> List = arrays.aslist (args);
        Collections.sort (list);
        SYSTEM.OUT.PRINTLN (list);
    }

Let's run this program.

args = {"%", "Java", "Sort", "I", "Walk", "the", "line"};
produces the following output.

[%, Sort, I, Java, line, the, walk]
This is a simple program, and the algorithms are really easy to use, just as they look.

The second form of sorting is to add the comparer in the list and sort the elements with the comparer. Suppose you want to print out the anagram group in the reverse order of the largest anagram group from our previous example. The following example shows you how to implement this with the help of the second form of the sort method.

Recall that the anagram group is stored as a list instance as a value in the map. The modified print code iterates through the mapped values view, putting each list of the minimum size tests into the list of lists. The code then sorts the list, uses the comparer for the desired list instance, and implements the reverse sort. Finally, the code traverses the sorted list and prints its elements (the anagram group). The following code replaces the print code at the end of the main method in the anagrams example.

Make a List of all anagram groups above size threshold.
List<list<string>> winners = new arraylist<list<string>> ();
For (list<string> l:m.values ())
    if (l.size () >= mingroupsize)
        Winners.add (l);

Sort anagram groups according to size
Collections.sort (winners, new comparator<list<string>> () { public
    int Compare (list<string> O1, list<string> O2) {return
        o2.size ()-o1.size ();
    }});

Print anagram groups.
for (list<string> l:winners)
    System.out.println (l.size () + ":" + L);

Run the program in the same dictionary as the Map Interface section, with the smallest anagram group size (8), which produces the following output.

[Apers, Apres, Asper, Pares, Parse, pears, prase, Presa, rapes, reaps, spare, spear] One: [Alerts, Alters, Artel S, Estral, Laster, Ratels, Salter, Slater, Staler, Stelar, talers]: [Least, Setal, slate, stale, steal, stela, t Aels, Tales, Teals, Tesla] 9: [Estrin, Inerts, insert, Inters, Niters, Nitres, Sinter, Triens, Trines] 9: [C Apers, Crapes, Escarp, Pacers, Parsec, recaps, scrape, secpar, spacer] 9: [Palest, palets, pastel, petals, plates, Pleats, septal, Staple, tepals] 9: [Anestri, Antsier, nastier, Ratines, retains, retinas, Retsina, Stainer,
       Stearin] 8: [Lapse, leaps, pales, peals, pleas, Salep, Sepal, Spale] 8: [Aspers, parses, passer, prases, repass, spares,  Sparse, Spears] 8: [Enters, Nester, Renest, rentes, resent, Tenser, Ternes, Treens] 8: [Arles, Earls, Lares, Laser, Lears, rales, reals, seral] 8: [Earings, erasing, gainers, Reagins, regains, Reginas, searing, Seringa] 8: [Peris, Piers, Pries, PRIse, Ripes, Speir, Spier, Spire] 8: [Ates, East, Eats, ETAs, sate, seat, SETA, teas] 8: [Carets, Cartes, Caster, caters, C Rates, reacts, recast, traces]
Shuffle (upset order)

The shuffle algorithm, in contrast to the sort, destroys any order that may appear in the list. That is, the algorithm rearranges the list according to the input from the random source, so that all possible permutations have the same possibility, assuming a reasonable randomness source. The algorithm has some reference value to realize the probability game. For example, it can be used to shuffle a list of card objects that represent a group. In addition, it helps generate test cases.

There are two forms of this operation: one using the list, using the default random source, and the other asking the caller to provide random objects as a source of randomness. The code for the algorithm is used as an example in the list section. General Data Operations

Collection classes provide five algorithms for performing regular data operations on List objects, which are simple: reverse-reverses the order of elements in a list. fill-overwrites each element in the list and has the specified value. This operation is useful for reinitialization of a list. copy-accepts two parameters, a target list and a source list, and copies the elements of the source to the target, overwriting its contents. The target list must be at least as long as the source code. If it is longer, the remaining elements in the target list are not affected. swap--the element at the specified position in the list. Addall-adds all the specified elements to the collection. The elements to be added can be specified individually or as arrays. Search

The BinarySearch algorithm searches for the specified element in the sorted list. There are two forms of the algorithm. The first gets a list and an element to search ("Search Key"). This form assumes that the list is sorted in ascending order according to the nature of its elements. The second form has a comparer in addition to the list and search keys, and assumes that the list is sorted in ascending order according to the specified comparer. The sort algorithm can sort the list before calling BinarySearch.

The return values are the same in both forms. If the list contains a search key, its index is returned. If not, the return value is (-(insertion point)-1), the value of the position of the insertion point is inserted into the list, or greater than the index value of the first element or list.size () if all the elements in the list are less than the specified value. This admittedly ugly formula guarantees that the return value will be >= 0 if and only if the search key is found. It basically combines a Boolean (found) and an integer (index) into an int return value method.

The following idioms can use two forms of binarysearch operations to find the specified search key and insert it in the appropriate location if it does not exist.

int pos = Collections.binarysearch (list, key);
if (POS < 0)
   L.add (-pos-1, key);
constitute

Frequency and disjoint algorithms test the components of one or more collections:

The frequency--count specifies the number of times the element occurs in the specified collection.
Disjoint-determines whether the two collections are separated, i.e. whether they contain the same elements. find the extreme value

The Min and Max algorithms return the smallest and largest elements contained in the specified collection, respectively. Both of these operations have two forms. This simple form accepts a collection and returns the smallest (or largest) element based on the natural sort of the element. The second form adds a comparer to the collection and returns the smallest (or largest) element based on the specified comparer.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.