快速排序之java实现

package com.cb.java.algorithms.datastructure.yanweimindatastructure.sort;


public class QuickSort<T extends Comparable<T>> {
/**
* 元素交换

* @param a
* @param b
*/
public void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}


/**
* 快速排序

* @param arr
* @param low
* @param high
*/
public void quickSort(T[] arr, int low, int high) {
int i = low; // 左哨兵
int j = high; // 右哨兵
if (low > high) {
return;
}


T temp = arr[low];
while (i < j) {
while (temp.compareTo(arr[j]) <= 0 && i < j) {
j--;
}
while (temp.compareTo(arr[i]) >= 0 && i < j) {
i++;
}
if (i < j) {
swap(arr, i, j);
}
}
arr[low] = arr[i];
arr[i] = temp;
quickSort(arr, 0, j - 1);
quickSort(arr, j+1 , high);
}


public static void main(String[] args) {
QuickSort<Integer> bubb = new QuickSort<>();
Integer[] arr = new Integer[] { 3, 2, 10, 5, 35, 27, 1000, 453, 34, 57, 89 };
bubb.quickSort(arr, 0, arr.length - 1);
for (Integer i : arr) {
System.out.print(i + " ");
}
}
}

猜你喜欢

转载自blog.csdn.net/u013230189/article/details/80679958