快速排序
/**
* className:Sort
*
* @author:zjl
* @version:0.1
* @date:2020/8/720:05
* @since:jdk1.8
*/
public class Sort {
//测试
public static void main(String[] args) {
int R[] = {1, 5, 9, 2, 6, 3, 7, 4, 8};
int[] ints = quickSort(R, 0, 8);
for (int i = 0; i < ints.length; i++) {
System.out.print(ints[i] + " ");
}
}
/**
* 快速排序
* @param R 待排序列
* @param low 待排序列的起点索引
* @param high 待排序列的终点索引
* @return
*/
public static int[] quickSort(int R[], int low, int high) {
int temp;//暂存基准元素
int i, j;
i = low;
j = high;
if (low < high) {
temp = R[low];
while (i < j) {
while (j > i && R[j] >= temp)//从j所指位置由右至左找到第一个比基准元素小的元素位置
j--;
if (i < j) {
R[i] = R[j];//插入到i所指位置
i++;
}
while (i < j && R[i] < temp)//从i所指位置由右至左找到第一个比基准元素大或者相等的元素位置
i++;
if (i < j) {
R[j] = R[i]; //插入到j所指位置
j--;
}
}
R[i] = temp;
quickSort(R, low, i - 1);//递归对基准元素左边的序列进行排序
quickSort(R, i + 1, high);//递归对基准元素右边的序列进行排序
}
return R;
}
}
测试结果