Java Sorting algorithm

Source: Internet
Author: User
Tags comparison final inheritance lowercase sort static class

Java 1.0 and 1.1 libraries are missing the same thing is arithmetic operations, not even the simplest method of sorting operations. Therefore, it is best to create a vector that uses the classic quicksort (Quick Sort) method to sort itself.
One of the problems with writing generic sorting code is that you have to perform comparison operations based on the actual type of the object to achieve the correct sort. One way to do this, of course, is to write a different sorting method for each of the different types. However, it should be recognized that if you do this, it is not easy to reuse code in the future by adding new types.
One of the main goals of programming is to "separate things that change from what remains unchanged". Here, the unchanging code is a generic sort algorithm, and each time you use it, you change the object's actual comparison method. Therefore, we cannot "Hard-code" the comparison code into several different sort routines, but instead adopt a "callback" technique. With callbacks, the part of the code that changes frequently is encapsulated within its own class, and the same code is "invoked" to "callback" the changed code. In this way, different objects can express different comparisons and pass the same sort code to them.
The following "interface" (Interface) shows how to compare two objects, which encapsulate "things to change":

: Compare.java
//Interface for sorting callback:
package c08;

Interface Compare {
  boolean LessThan (Object LHS, Object RHS);
  Boolean Lessthanorequal (Object LHS, Object RHS);
///:~


For both methods, LHS represents the "left-handed" object in this comparison, and the RHS represents the "right" object.
You can create a subclass of a vector that enables quick sorting by compare. For this algorithm, including its speed and principle, and so on, not specifically described here. For more information, refer to Binstock and Rex's "Practical Algorithms for Programmers", published by Addison-wesley in 1995.

//: Sortvector.java//A generic sorting vector package c08; import java.util.*; public class Sortvector extends Vector {private Compare Compare;//To hold the callback public Sortvector (Compare Co
  MP) {compare = comp;
  public void sort () {quickSort (0, size ()-1);
      private void QuickSort (int left, int right) {if (right > left) {Object O1 = ElementAt (right);
      int i = left-1;
      int j = right;
        while (true) {while (Compare.lessthan ElementAt (++i), O1)); while (J > 0) if (compare.lessthanorequal (ElementAt (--j), O1)) the break;
        Out of the while if (I >= j) break;
      Swap (I, j);
      Swap (I, right);
      QuickSort (left, i-1);
    QuickSort (i+1, right);
    } private void Swap (int loc1, int loc2) {Object tmp = ElementAt (LOC1);
    Setelementat (ElementAt (LOC2), Loc1);
  Setelementat (TMP, LOC2); }
} ///:~


Now you can see the origin of the word "callback" because the Quicksort () method "calls back" the method in compare. It also helps to understand how this technology generates generic, reusable (regenerated) code.
To use Sortvector, you must create a class that implements compare for the object we are preparing to sort. The inner class is not particularly important at this point, but it is useful for the organization of the Code. The following is an example of a string object:
 

//: Stringsorttest.java//testing the generic sorting Vector package c08; import java.util.*; public class Stringsorttest {static Class Stringcompare implements Compare {public boolean LessThan (Object L, Obje
    CT r) {return ((string) L). toLowerCase (). CompareTo (((String) R). toLowerCase ()) < 0;
        public boolean Lessthanorequal (object L, Object R) {return ((String) L). toLowerCase (). CompareTo (
    ((String) R). toLowerCase ()) <= 0;
    } public static void Main (string[] args) {Sortvector SV = new Sortvector (new Stringcompare ());
    Sv.addelement ("D");
    Sv.addelement ("A");
    Sv.addelement ("C");
    Sv.addelement ("C");
    Sv.addelement ("B");
    Sv.addelement ("B");
    Sv.addelement ("D");
    Sv.addelement ("a");
    Sv.sort ();
    Enumeration E = Sv.elements ();
  while (E.hasmoreelements ()) System.out.println (E.nextelement ()); }
} ///:~

The


Inner class is static because it works without having to connect an external class.
You can see that once you've set up a frame, you can easily reuse a design like this-simply write a class, encapsulate something that needs to change, and then pass an object to Sortvector.
The string is coerced to lowercase when compared, so uppercase A is arranged next to lowercase a and does not move a completely different place. However, this example also shows an insufficiency of this method, because the test code arranges the uppercase and lowercase forms of the same letter in the order in which they appear: a a b b c c d. But this is usually not a big deal, because it's often a longer string, so the effect won't be revealed (the Java 1.2 collection provides sorting, which solves the problem).
Inheritance (extends) is used here to create a new type of vector--that is to say, Sortvector belongs to a vector with some additional functionality. Inheritance can play a big role here, but it brings problems. It makes some methods have final attributes (already covered in chapter 7th), so they cannot be overwritten. If you want to create a sequenced vector so that it receives and generates only string objects, you will get into trouble. Because AddElement () and ElementAt () have final attributes, and they are all methods that we must override, we cannot implement a string object that can only be received and generated.
But on the other hand, consider using the "compositing" method: Placing an object inside a new class. At this point, instead of rewriting the code to achieve this, you simply use a sortvector in the new class. In this case, the inner class used to implement the Compare interface can be created "anonymously". As follows:
 

: Strsortvector.java//automatically sorted Vector that//accepts and produces only Strings package c08;

Import java.util.*;
      public class Strsortvector {private Sortvector v = new Sortvector (//Anonymous inner class:new Compare () {
          public boolean LessThan (object L, Object R) {return ((String) L). toLowerCase (). CompareTo (
      ((String) R). toLowerCase ()) < 0; public boolean Lessthanorequal (object L, Object R) {return ((String) L). toLowerCase (). Co
      Mpareto (((String) R). toLowerCase ()) <= 0;
  }
    }
  );
  Private Boolean sorted = false;
    public void AddElement (String s) {v.addelement (s);
  sorted = false;
      Public String elementat (int index) {if (!sorted) {v.sort ();
    sorted = true;
  Return (String) v.elementat (index);
      Public enumeration elements () {if (!sorted) {v.sort ();
    sorted = true;
return v.elements ();  }//Test it:public static void Main (string[] args) {Strsortvector SV = new Strsortvector ();
    Sv.addelement ("D");
    Sv.addelement ("A");
    Sv.addelement ("C");
    Sv.addelement ("C");
    Sv.addelement ("B");
    Sv.addelement ("B");
    Sv.addelement ("D");
    Sv.addelement ("a");
    Enumeration E = Sv.elements ();
  while (E.hasmoreelements ()) System.out.println (E.nextelement ()); }
} ///:~

This allows you to quickly regenerate code from Sortvector to get the desired functionality. However, not all public methods from sortvector and vectors can appear in the Strsortvector. If you reproduce the code in this form, you can generate a definition for each method within the containing class in the new class. Of course, you can add only a few at the beginning, and then add more if you need to. The design of the new class will eventually stabilize.
The advantage of this approach is that it still accepts only string objects and only String objects. And the corresponding checks are made during compilation, not at run time. Of course, only addelement () and ElementAt () have this feature; elements () still produces a enumeration (enumeration), and its type is undefined at compile time. Of course, the enumeration as well as the type checks in the Strsortvector will go on as usual; if there is a real mistake, the runtime will simply create an error. In fact, do we ensure that everything is correct during compilation or operation? (That is, "the code test may not be guaranteed", and "the user of the program might do something without our testing"). Although there are other options and arguments, it is much easier to use inheritance, but it is very inconvenient when it comes to styling. In the same way, once you add a parameterized type to Java, you are expected to solve this problem.
You can see a flag named "Sorted" in this class. Vectors can be sorted each time the addelement () is invoked and kept in a sequential state. But before you start reading, people always add a large number of elements to a vector. So instead of sorting after each addelement (), it's better to wait until someone wants to read the vector and then sort it. The latter is much more efficient. This method of inaction, unless absolutely necessary, is called "lazy evaluation" (there is a similar technique called "lazy initialization" – no initialization unless a field value is really needed).

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.