欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java 快速排序

程序员文章站 2022-03-24 13:15:48
...

import java.util.Random;

/**
*
* @author liebaorun liu
*
* @param <T>
*/

public class QuickSortUtil<T extends Comparable<T>> {


public void quickSort(T[] arr, int start, int end){


if(start >= end) return;

int middle = start;
int pointerI = start;


for( ; pointerI < end; pointerI++){
if(arr[pointerI].compareTo(arr[end]) > 0){
swap(arr,middle++,pointerI);
}
}

swap(arr,middle,end);

quickSort(arr,start,middle-1);
quickSort(arr,middle+1,end);
}

private void swap(T[] arr, int i, int j){
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}




public static void main(String[] args){

Integer[] arr = new Integer[100];

QuickSortUtil<Integer> qut = new QuickSortUtil<Integer>();

Random random = new Random();
for(int i=0; i<arr.length; i++){
arr[i] = new Integer(random.nextInt(20));
System.out.print(arr[i] + " ");
}

//int[] arr1 = new int[10];
qut.quickSort(arr, 0, arr.length-1);

System.out.println();

for(int i=0; i<arr.length; i++){
System.out.print(arr[i] + " ");
}

qut.quickSort(arr, 0, arr.length-1);

System.out.println();

for(int i=0; i<arr.length; i++){
System.out.print(arr[i] + " ");
}

}

}
相关标签: Java J#