# 6. 三向切分快速排序

java

```java
//排序抽象类
public abstract class Sort<T extends Comparable<T>> {
    public abstract void sort(T[] nums);

    public boolean less(T v,T w){
        return v.compareTo(w)<0;
    }

    public void swap(T[] a,int i,int j){
        T t=a[i];
        a[i]=a[j];
        a[j]=t;
    }
}

//快速排序，继承排序
public class QuickSort<T extends Comparable<T>> extends Sort<T> {
    @Override
    public void sort(T[] nums) {
        shuffle(nums);
        sort(nums,0,nums.length-1);
    }

    public void sort(T[] nums,int l,int h){
        if(l>=h) return;
        int j=partition(nums,l,h);
        sort(nums,l,j-1);
        sort(nums,j+1,h);
    }

    public int partition(T[] nums,int l,int h){
        int i=l,j=h+1;
        T v=nums[l];
        while(true){
            while(j!=l&&less(v,nums[--j]));
            while(i!=h&&less(nums[++i],v));
            if(i>=j) break;
            swap(nums,i,j);
        }
        swap(nums,l,j);
        return j;
    }

    public void shuffle(T[] nums){
        List<Comparable> list=Arrays.asList(nums);
        Collections.shuffle(list);
        list.toArray(nums);
    }
}

// 三切分快速排序，继承快速排序
public class ThreeWayQuickSort<T extends Comparable<T>> extends QuickSort<T> {
    @Override
    public void sort(T[] nums, int l, int h) {
        if(l>=h) return;
        int lt=l,i=l+1,gt=h;
        T v=nums[l];
        System.out.println(v);
        while (i<=gt){
            int compare=nums[i].compareTo(v);
            if(compare<0){
                swap(nums,lt++,i++);
            }else if(compare>0){
                swap(nums,i,gt--);
            }else {
                i++;
            }
        }
        sort(nums,l,lt-1);
        sort(nums,gt+1,h);
    }

    public static void main(String[] args){
        Integer[] arr={
                5,1,8,1,3,3,3,3,5,5,8,8,8
        };
        ArrayUtils.printArray(arr);
        Sort<Integer> sort=new ThreeWayQuickSort<>();
        sort.sort(arr);
        ArrayUtils.printArray(arr);
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://im-qianuxn.gitbook.io/pytorch/ji-suan-ji/shua-ti/pai-xu-lei/6-san-pei-fen-kaui-pai.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
