1. 程式人生 > 實用技巧 >QuickSearch快排

QuickSearch快排



import java.util.Scanner;

/**
* @program:
* @description:
* @author: Jay
* @create: 2020-09-21 19:23
**/
public class QuickSearch {
public static void QKsort(int[] arr, int low, int high) {
if (low < high) {
int pos = QKpass(arr, low, high); //劃分兩個子表
QKsort(arr, low, pos - 1); //對左子錶快排
QKsort(arr, pos + 1, high); //對右子錶快排
}
}

/**
* 一趟快速排序演算法
*
* @param arr 待排序陣列
* @param low 陣列開始下標
* @param
* @return
*/
public static int QKpass(int[] arr, int low, int high) {
int temp = arr[low]; //先把當前元素作為待排值(一趟排序實際上就是把它放到合適的位置)
while (low < high) {
while (low < high && arr[high] >= temp) //從右向左掃描,找到第一個小於temp的值
{
high--;
}
if (low < high) { //將此值放入下標為low的陣列中
arr[low] = arr[high];
low++;
}
while (low < high && arr[low] <= temp) //從左向右掃描找到第一個大於temp的值
{
low++;
}
if (low < high) {
arr[high] = arr[low]; //放在下標為high的陣列中
high--;
}
}
arr[low] = temp; //將此元素放入其準確位置
return low; //返回此次排序完成的值當前下標(即此位置的元素已經排好)
}

public static void main(String[] args) {
int[] arr = new int[10];
Scanner sc = new Scanner(System.in);
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
sc.close();
QKsort(arr, 0, arr.length - 1);
for (int x : arr) {
System.out.print(x + " ");
}
}
}