Java Sorting and searching

Source: Internet
Author: User
Tags arrays character set comparable comparison int size integer lowercase sort

Java 1.2 adds its own set of utilities that you can use to arrange and search for arrays or lists. These tools all belong to the "static" method of two new classes. These two classes are arrays for sorting and searching arrays, and collections for sorting and searching lists. The

1. Array
Arrays class provides an overloaded sort () and binarysearch () for arrays of all base data types, and can also be used for string and object. The following example shows how to sort and search a byte array (all other basic data types are similar) and a string array:
 

: Array1.java//testing the sorting & searching in Arrays package c08.newcollections;

Import java.util.*;
  public class Array1 {static Random R = new Random ();
  static String ssource = "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz";
  static char[] src = ssource.tochararray ();
    Create a random string public static string randstring (int length) {char[] buf = new Char[length];
    int Rnd;
      for (int i = 0; i < length; i++) {rnd = Math.Abs (R.nextint ())% Src.length;
    Buf[i] = Src[rnd];
  Return to New String (BUF); //Create a random array of strings:public static string[] randstrings (int length, int size) {string[] s =
    New String[size];
    for (int i = 0; i < size; i++) s[i] = randstring (length);
  return s;
    public static void print (byte[] b) {for (int i = 0; i < b.length; i++) System.out.print (B[i] + "");
  System.out.println (); public static void print (string[] s) {
    for (int i = 0; i < s.length i++) System.out.print (S[i] + "");
  System.out.println ();
    public static void Main (string[] args) {byte[] b = new BYTE[15]; R.nextbytes (b);
    Fill with random bytes print (b);
    Arrays.sort (b);
    Print (b);
    int loc = Arrays.binarysearch (b, b[10]);
    System.out.println ("Location of" + b[10] + "=" + loc);
    Test String Sort & search:string[] s = randstrings (4, 10);
    print (s);
    Arrays.sort (s);
    print (s);
    LOC = Arrays.binarysearch (S, s[4]);
  System.out.println ("Location of" + s[4] + "=" + loc); }
} ///:~

The first part of the class contains a utility for generating random string objects, and the random letters available for selection are stored in a character array. Randstring () returns a string of any length, while readstrings () creates an array of random strings, given the length of each string and the size of the desired array. The two print () method simplifies the display of the model array. In Main (), Random.nextbytes () fills the array arguments with randomly selected bytes (no corresponding Random method is used to create an array of other base data types). Once you have an array, you can see that you only need to make a method call to perform the sort () or binarysearch (). Another important caveat associated with binarysearch () is that unpredictable behavior occurs, including infinite loops, if you do not call sort () before you perform a binarysearch ().
The sort of string and search are similar, but when running the program, we notice an interesting phenomenon: the sort follows the dictionary order, which means that uppercase letters precede the lowercase letters in the character set. Therefore, all uppercase letters are at the top of the list, followed by a lowercase letter--z in front of a. It seems that even the phone book is sorted like this.

2. Comparable and comparator
But if we do not satisfy this sort of arrangement, how should we deal with it? For example, the index at the back of this book, if you have to view the entries that start with a or a, to two places, will certainly make the reader quite impatient.
If you want to sort an array of object, you must solve a problem. Based on what determines the order of two object? Unfortunately, the original Java designer didn't think it was an important issue, otherwise it was already defined in the root class object. One consequence of this is that the object must be sorted externally, and the new collection library provides the standard way to do so (ideally it is defined in object).
For an object array (and string, of course, it belongs to object), you can use a sort () and accept another parameter: one that implements the comparator interface (that is, the comparer interface, part of the new collection Library), It is compared with its single compare () method. This method uses two objects that are to be compared as their own arguments--if the first argument is less than the second, returns a negative integer; if equal, returns 0; if the first argument is greater than the second, a positive integer is returned. Based on this rule, the string portion of the above example can be written back to make it truly alphabetical in order:

//: Alphacomp.java//Using Comparator to perform a alphabetic sort package; c08.newcollections

RT java.util.*; public class Alphacomp implements Comparator {public int compare (object O1, Object O2) {//Assume it's used only F
    Or Strings ...
    string S1 = ((String) O1). toLowerCase ();
    String s2 = ((String) O2). toLowerCase ();
  return S1.compareto (S2);
    public static void Main (string[] args) {string[] s = array1.randstrings (4, 10);
    Array1.print (s);
    Alphacomp ac = new Alphacomp ();
    Arrays.sort (S, AC);
    Array1.print (s);
    Must use of the Comparator to search, Also:int loc = Arrays.binarysearch (S, s[3], AC);
  System.out.println ("Location of" + s[3] + "=" + loc); }
} ///:~

The


String,compare () method makes "hint" tests that make sure that only string objects are being manipulated-the runtime system catches any errors. After you force the two strings into lowercase, the String.CompareTo () method produces the expected results.
If you use your own comparator to do a sort (), you must use the same comparator when using BinarySearch (). The
Arrays class provides another sort () method that takes a single argument: an Object array, but no comparator. The sort () method must also compare two object in the same way. By implementing the comparable interface, it uses a "natural comparison method" that assigns a class. This interface contains a single method--compareto () that can be used to compare objects by returning negative, 0, or positive numbers, depending on its value less than, equal to, or greater than the argument. The following example simply illustrates this point:
 

//: Compclass.java//A class that implements comparable package c08.newcollections; Import java.util

.*;
  public class Compclass implements comparable {private int i;
  Public Compclass (int ii) {i = II}
    public int compareTo (Object o) {//implicitly tests for correct type:int Argi = ((Compclass) O). I;
    if (i = = Argi) return 0;
    if (i < argi) return-1;
  return 1;
    public static void print (object[] a) {for (int i = 0; i < a.length; i++) System.out.print (A[i] + "");
  System.out.println ();
  Public String toString () {return i + "";}
    public static void Main (string[] args) {compclass[] a = new compclass[20];
    for (int i = 0; i < a.length i++) a[i] = new Compclass ((int) (Math.random () *100));
    Print (a);
    Arrays.sort (a);
    Print (a);
    int loc = Arrays.binarysearch (A, a[3]);
  System.out.println ("Location of" + a[3] + "=" + loc); }
} ///:~


Of course, our CompareTo () method can also increase complexity according to the actual situation.

3. The list
can be sorted and searched in the same form as an array (list). static methods for sorting and searching lists are contained in class collections, but they have the same signature as arrays: sort (list) is used to sort a list of objects that implement comparable; BinarySearch (list, object is used to find a list of objects; sort (list,comparator) sorts a list by using a comparer; BinarySearch (List,object,comparator) is used to find an object in that list (note ⑨). The following example uses predefined Compclass and Alphacomp to demonstrate the various sorting tools in collections:
 

: Listsort.java//sorting and searching Lists with ' collections ' package c08.newcollections;

Import java.util.*;
    public class Listsort {public static void main (string[] args) {final int SZ = 20;
    Using "Natural Comparison Method": List a = new ArrayList ();
    for (int i = 0; i < SZ; i++) A.add (New Compclass ((int) (Math.random () *100));
    Collection1.print (a);
    Collections.sort (a);
    Collection1.print (a);
    Object find = A.get (SZ/2);
    int loc = Collections.binarysearch (A, find);
    System.out.println ("Location of" + find + "=" + loc);
    Using a comparator:list b = new ArrayList ();
    for (int i = 0; i < SZ; i++) B.add (array1.randstring (4));
    Collection1.print (b);
    Alphacomp ac = new Alphacomp ();
    Collections.sort (b, AC);
    Collection1.print (b);
    Find = B.get (SZ/2);
    Must use of the Comparator to search, Also:loc = Collections.binarysearch (b, Find, AC); System.out.println ("Locationof "+ find +" = "+ loc);  }
} ///:~

⑨: At the time of writing, a new Collections.stablesort () has been announced, which can be used for merge sorting, but no beta version has been published.

The usage of these methods is exactly the same as that used in arrays, except that the array is replaced with a list.
TreeMap must also sort their objects according to comparable or comparator.

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.