Home  >  Article  >  Java  >  Detailed explanation of how to use generics to implement quick sorting algorithm in Java

Detailed explanation of how to use generics to implement quick sorting algorithm in Java

高洛峰
高洛峰Original
2017-01-19 09:19:051021browse

Quick sort algorithm concept
Quick sort is generally based on recursive implementation. The idea is as follows:
1. Select a suitable value (ideally the median value is the best, but in implementation the first value of the array is generally used), which is called the "pivot".
2. Based on this value, divide the array into two parts, with the smaller one on the left and the larger one on the right.
3. It is certain that after this round, the position of this pivot must be at the final position.
4. Repeat the above process for the two sub-arrays until each array has only one element.
5. Sorting completed.

Basic implementation method:

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);    //将数组分为两部分
    qsort(arr, low, pivot-1);          //递归排序左子数组
    qsort(arr, pivot+1, high);         //递归排序右子数组
  }
}
private static int partition(int[] arr, int low, int high){
  int pivot = arr[low];   //枢轴记录
  while (low=pivot) --high;
    arr[low]=arr[high];       //交换比枢轴小的记录到左端
    while (low

Use generics to implement the quick sort algorithm

The following design a QuickSort class, including The static function sort() can sort arrays of any type. If it is an array of object type, the object type must implement the Comparable interface so that the compareTo function can be used for comparison.

The most basic quick sort algorithm is used without optimization.

The source code is as follows:

import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;
  
public class QuickSort {
  @SuppressWarnings("unchecked")
  //对上述快排函数原型修改,使其可以对任意对象类型数组进行排序。这个函数为内部使用,外部排序函数接口为sort(),sort函数要求对象必须实现Comparable接口,可以提供编译时类型检测,见后文。
  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++) {
      //该对象类型数组必须实现Comparable接口,这样才能使用compareTo函数进行比较
      if( ((Comparable)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;
  }
    
  //使用泛型,对任意对象数组排序,该对象类型数组必须实现Comparable接口
  public static > void sort(T[] input){
    quickSort(input,0,input.length);
  }
    
  //添加对List对象进行排序的功能,参考了Java中的Java.util.Collections类的sort()函数
  public static > void sort(List list){
    Object[] t = list.toArray();//将列表转换为数组
    quickSort(t,0,t.length); //对数组进行排序
    //数组排序完成后再写回到列表中
    ListIterator i = list.listIterator();
    for (int j=0; j l = new LinkedList();
    s = new String[]{"b","a","e","d","f","c"};
    System.out.print("LinkedList before sorting: ");
    for (int j=0; j after sorting: ");
    for (String ts : l) {
      System.out.print(ts + " ");
    }
    System.out.println();
  }
}

Run the main function test. From the output, you can see that the QuickSort class is working normally:

int[] before sorting: 65 48 92 26 3 8 59 21 16 45
int[] after sorting: 3 8 16 21 26 45 48 59 65 92
String[] before sorting: b a e d f c
String[] after sorting: a b c d e f
LinkedList before sorting: b a e d f c
LinkedList after sorting: a b c d e f

More details in Java For related articles on how to implement quick sorting algorithm using generics, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn