package com.suifeng.sort;
public class QuickSort {
public static void main(String[] args) {
int[] nums = { 49, 38, 65, 97, 76, 13, 27 };
System.out.println("=============排序前=============");
//显示排序后的数组
for (int i = 0; i < nums.length; ++i) {
System.out.print(nums[i] + ",");
}
System.out.println();
//应用快速排序方法
sort(nums, 0, nums.length - 1);
System.out.println("=============排序前=============");
//显示排序后的数组
for (int i = 0; i < nums.length; ++i) {
System.out.print(nums[i] + ",");
}
System.out.println("");
}
public static void sort(int[] arr, int low, int high)
{
int lo = low;
int hi = high;
if(low >= high)
{
return;
}
// 默认从后往前数
boolean flag = true;
while(low < high)
{
// 碰到后边比关键码大的值,交换该值与关键码的位置
if(arr[low] > arr[high])
{
int temp = arr[low];
arr[low] = arr[high];
arr[high] = temp;
// 重置下标移动方向
flag = !flag;
}
if(flag)
{
// 关键码在arr[low]处
high--;
}
else
{
// 关键码在arr[high]
low++;
}
}
high++;
low--;
sort(arr,lo,low);
sort(arr,high,hi);
}
}
执行结果:
=============排序前=============
49,38,65,97,76,13,27,
=============排序后=============
13,27,38,49,65,76,97,