Detailed Java method to implement a fast sort algorithm using generics _java

Source: Internet
Author: User
Tags comparable function prototype

The concept of fast sorting algorithm
fast sorting is generally based on recursive implementations. The idea is this:
1. Select a suitable value (ideally, the value is the best, but the first value of the array is generally used in the implementation), called "pivot" (pivot).
2. Based on this value, the array is divided into two parts, the smaller one on the left and the larger on the right.
3. To be sure, such a round down, this pivot position must be in the final position.
4. Repeat the above procedure for each of the two sub arrays until there is only one element per array.
5. Sorting completed.

Basic implementation methods:

public static void QuickSort (int[] arr) {
  qsort (arr, 0, arr.length-1);
}
private static void Qsort (int[] arr, int low, int high) {
  if (Low < high) {
    int pivot=partition (arr, low, high); c6/>//the array into two parts
    qsort (arr, Low, pivot-1);          Recursive sort left sub array
    qsort (arr, pivot+1, high);         Recursive sort right sub array
  }
}
private static int partition (int[] arr, int low, int high) {
  int pivot = arr[low];
   
    //Pivot Record while
  (Low

Using generics to implement a fast-scheduling algorithm

The following design is a quicksort class that contains a static function sort () that can sort an array of any type. If an array of object types, the object type must implement the comparable interface in order to be compared using the CompareTo function.

Using the most basic fast algorithm, no optimization processing.

The source code is as follows:

Import java.util.LinkedList;
Import java.util.List;
Import Java.util.ListIterator;
 
Import Java.util.Random; The public class QuickSort {@SuppressWarnings ("unchecked")//modifies the above quick-order function prototype so that it can sort an array of arbitrary object types.
  This function is used internally, the external sort function interface is sort (), the sort function requires the object to implement the comparable interface, and can provide compile-time type detection, see later.
    private static void QuickSort (object[] in,int begin, int end) {if (begin = = End | | begin = = (end-1)) return;
    Object p = In[begin];
    int a = begin +1;
    int b = A; for (; b < end; b++) {//The object type array must implement the comparable interface so that the CompareTo function can be used to compare if ((comparable<object>) in[b]
        ). CompareTo (P) < 0) {if (a = = b) {a++; continue;}
        Object temp = In[a];
        In[a] = in[b];
        IN[B] = temp;
      a++;
    }} In[begin] = In[a-1];
    In[a-1] = p;
    if (A-1 > Begin) {quickSort (In,begin, a);
    } if (End-1 > a) {quickSort (in,a, end);
  } return; ///Use generics to sort arbitrary array of objects, the object type array must implement the comparable interface public static <t extends Comparable<?
  Super t>> void sort (t[] input) {quickSort (input,0,input.length); //Add the ability to sort the list objects, referring to the sort () function of the Java.util.Collections class in Java, public static <t extends Comparable<? Super t>> void Sort (list<t> list) {object[] T = List.toarray (),//Convert list to array quickSort (T,0,T.LENGTH);
    The array is sorted//array sorted and then written back to the list listiterator<t> i = List.listiterator ();
      for (int j=0; j<t.length; J + +) {i.next ();
    I.set ((T) t[j]); Because the original data type (int, double, byte, and so) in Java cannot use generics, you can only use the function overload mechanism to sort the array of primitive types (int[], double[], byte[], and so on. In order to share the same sort function, we use the original type (autoboxing,unboxing) mechanism to encapsulate it as the corresponding object type, form a new object array, and then unpack the package after sorting, the disadvantage is that additional conversion steps and extra space are needed to save the encapsulated array.
  Another way is to copy the sort code into each overloaded function, which is used by the sort () function in the Java.util.Arrays class in the official API, which can be seen from the source code of the Arrays class.
    public static void sort (int[] input) {integer[] t = new integer[input.length]; for (int i = 0; i < input.length i++) {T[i] = input[i];//Encapsulation} quickSort (t,0,t.length);//Sort for (int i = 0; I < Input.length; i++) {Input[i] = t[i];//solution Encapsulation}//double[] array overloaded functions public static void sort (double[] input) {double[] t
    = new Double[input.length];
    for (int i = 0; i < input.length i++) {t[i] = Input[i];
    } quickSort (T,0,t.length);
    for (int i = 0; i < input.length i++) {input[i] = T[i];
    The overloaded functions of the//byte[] array are public static void sort (byte[] input) {byte[] t = new byte[input.length];
    for (int i = 0; i < input.length i++) {t[i] = Input[i];
    } quickSort (T,0,t.length);
    for (int i = 0; i < input.length i++) {input[i] = T[i];
    The overloaded functions of the//short[] array are public static void sort (short[] input) {short[] t = new short[input.length];
    for (int i = 0; i < input.length i++) {t[i] = Input[i];
    } quickSort (T,0,t.length);
    for (int i = 0; i < input.length i++) {input[i] = T[i]; overloaded functions of}//char[] array public static void sort (char[] input) {character[] t = new ChaRacter[input.length];
    for (int i = 0; i < input.length i++) {t[i] = Input[i];
    } quickSort (T,0,t.length);
    for (int i = 0; i < input.length i++) {input[i] = T[i];
    The overloaded functions of the//float[] array are public static void sort (float[] input) {float[] t = new float[input.length];
    for (int i = 0; i < input.length i++) {t[i] = Input[i];
    } quickSort (T,0,t.length);
    for (int i = 0; i < input.length i++) {input[i] = T[i];
    }///test main function public static void main (string[] args) {//To produce a random number of int[] array, used to test int LEN = 10;
    int[] input = new Int[len];
    Random r = new Random ();
    System.out.print ("int[] before sorting:");
      for (int i = 0; i < input.length i++) {Input[i] = R.nextint (10*len);
    System.out.print (Input[i] + "");
    } System.out.println ();
    System.out.print ("int[] after sorting:");
    sort (input);
    for (int i:input) {System.out.print (i + ""); } SystEm.out.println ();
    Generates an array of strings to test string[] s = new string[]{"B", "A", "E", "D", "F", "C"};
    System.out.print ("string[] before sorting:");
    for (int i = 0; i < s.length i++) {System.out.print (S[i] + "");
    } System.out.println ();
    System.out.print ("string[] after sorting:");
    Sort (s);
    for (int i = 0; i < s.length i++) {System.out.print (S[i] + "");
     
    } System.out.println ();
    Generates a list of strings to test list<string> L = new linkedlist<string> ();
    s = new string[]{"B", "A", "E", "D", "F", "C"};
    System.out.print ("Linkedlist<string> before sorting:");
      for (int j=0; j<s.length; J + +) {L.add (s[j));
    System.out.print (S[j] + "");
    } System.out.println ();
    Sort (l);
    System.out.print ("Linkedlist<string> after sorting:");
    for (String ts:l) {System.out.print (ts + "");
  } System.out.println ();

 }
}

Running the main function test, you can see from the output that the Quicksort class is working correctly:

Int[] before sorting:65 3 8 int[] after Sorting:3 8 (a) (string[
) before Sorting:b A E d f c 
string[] after sorting:a b c d E F 
linkedlist<string> before sorting:b A E d f c
   
    linkedlist<string> after Sorting:a b c D E F

   

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.