用java实现的快速排序算法
之前看到的一道关于java快速排序的算法,由于个人也不是很明白,于是在网上找了几个现成的代码,结果测试发现了一些问题,于是稍加改进,如果还有问题请大家指出
public class TestInterview {
/**
* 快速排序
*
* @param strDate
* @param left
* @param right
*/
public void quickSort(int[] strDate, int left, int right) {
int middle, tempDate;
int i, j;
i = left;
j = right;
middle = strDate[left];
do {
//修改之前代码 本人这里只对整数排序
/*while (strDate[i].compareTo(middle) < 0 && i < right)
i++; // 找出左边比中间值大的数
while (strDate[j].compareTo(middle) > 0 && j > left)
j--; // 找出右边比中间值小的数*/
while (i < right){
if(strDate[i]<middle){
i++; // 找出左边比中间值大的数
}
else break;
}
while (j > left){
if(strDate[j]>middle){
j--; // 找出右边比中间值小的数
}
else break;
}
if (i <= j) { // 将左边大的数和右边小的数进行替换
tempDate = strDate[i];
strDate[i] = strDate[j];
strDate[j] = tempDate;
i++;
j--;
}
} while (i <= j); // 当两者交错时停止
if (i < right) {
quickSort(strDate, i, right);// 从
}
if (j > left) {
quickSort(strDate, left, j);
}
}
/**
* @param args
*/
public static void main(String[] args) {
int[] strVoid = new int[] { 1, 2, 3, 10, 6, 7, 8 };
TestInterview sort = new TestInterview();
sort.quickSort(strVoid, 0, strVoid.length - 1);
for (int i = 0; i < strVoid.length; i++) {
System.out.println(strVoid[i] + " ");
}
}
}