# Java与算法之(2) - 快速排序

4870人阅读 评论(0)

2 3 1

7 6 5

public class QuickSort {

public void sort(int left, int right, int... numbers) {
if (left >= right) {
return;
}
int temp = numbers[left];
int t = 0;
int i = left;
int j = right;
while (i != j) {
// 先从右往左找
while (numbers[j] >= temp && i < j)
j--;
// 再从左往右找
while (numbers[i] <= temp && i < j)
i++;
// 交换两个数在数组中的位置
if (i < j) {
t = numbers[i];
numbers[i] = numbers[j];
numbers[j] = t;
}
}
// 将基准数归位
numbers[left] = numbers[i];
numbers[i] = temp;

sort(left, i - 1, numbers);
sort(i + 1, right, numbers);
}
}

	public static void main(String[] args) {
int[] numbers = new int[] { 4, 3, 6, 2, 7, 1, 5 };

new QuickSort().sort(0, numbers.length - 1, numbers);

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

after: 1  2  3  4  5  6  7


	public void sortWithoutRecursion(int left, int right, int... numbers) {
int index;
stack.push(left);
stack.push(right);
while (!stack.isEmpty()) {
right = stack.pop();
left = stack.pop();
index = partition(left, right, numbers);
if (left < index - 1) {
stack.push(left);
stack.push(index - 1);
}
if (right > index + 1) {
stack.push(index + 1);
stack.push(right);
}
}
}

public int partition(int left, int right, int... numbers) {
int temp = numbers[left];
while (left < right) {
while (numbers[right] >= temp && left < right)
right--;
numbers[left] = numbers[right];
while (numbers[left] <= temp && left < right)
left++;
numbers[right] = numbers[left];
}
numbers[left] = temp;
return left;
}

0
1

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：440023次
• 积分：3957
• 等级：
• 排名：第8212名
• 原创：54篇
• 转载：1篇
• 译文：0篇
• 评论：58条
博客专栏
 Java与算法 文章：13篇 阅读：54500
文章分类
最新评论