JAVA排序之快速排序法(源自张孝祥面试题)

来源:互联网 发布:js search汉字 编辑:程序博客网 时间:2024/05/16 09:04
/** * 快速排序法 * @author Shoper */public class QuickSortTest { public static void main(String[] args) {  Integer[] array = new Integer[] { 12, 44, 12, 13, 14, 0, 67, 12, 53 };  System.out.println("原始数据");  for (Integer integer : array) {   System.out.print(integer+",");  }  // 数组刚开始,还未排序。传入的的数据为:数组,从哪个位置开始排序,到什么位置结束  System.out.println("\n排序后");  new QuickSortTest().sortFactory(array, 0, array.length-1 );  for (Integer integer : array) {   System.out.print(integer+",");  } } public void sortFactory(Integer[] array, Integer left, Integer right) {  Integer start = left;  Integer end = right;  /*这里是重点(right+left)/2。   *我之前在这里出错找了很久.middle要取数组中间那个元素才行。之前都写成(array.length+1)/2。   *错误情况下排序,结果造成了排序对比的元素不正确。   */  Integer middle = array[(right + left) / 2];  Boolean isEnd = false;  Integer tempDate;  while (!isEnd) {   // 找出左边比中间值大的数,如果没有则继续循环   while (array[start].compareTo(middle) < 0 && start < right) {    start++;    }   // 找出右边比中间值大的数,如果没有则继续循环   while (array[end].compareTo(middle) > 0 && end > left) {    end--;    }   // 将左边大的数和右边小的数进行替换   if (start <= end) {     tempDate= array[start];    array[start] = array[end];    array[end] = tempDate;    start++;    end--;   }   if (!(start <= end)) {    isEnd = true;   }  }  if (start < right) {   sortFactory(array, start, right);  }  if (end > left) {   sortFactory(array, left, end);  } }}