Java快速排序
最近在学习快速排序,把自己写的代码copy下来
package main;
import java.util.Scanner;
public class Main {
public static void sort(int[] a, int begin,int last) {
int start = begin;
int end = last;
int key = a[begin];
while (end > start) {
while (end > start && a[end] >= key) {
end--;
}
if (a[end] <= key) {
int temp = a[end];
a[end] = a[start];
a[start] = temp;
}
while (end > start && a[start] <= key) {
start++;
}
if (a[start] >= key) {
int temp = a[start];
a[start] = a[end];
a[end] = temp;
}
}
if (start > begin)
sort(a, begin, start - 1);
if (end < last)
sort(a, end + 1, last);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] t = new int[n];
for (int i = 0; i < n; i++) {
t[i]=sc.nextInt();
}
System.out.println("快速排序:");
int start = 0;
int end = t.length - 1;
sort(t, start, end);
for (int i = 0; i < n; i++) {
System.out.print(t[i] + " ");
}
}
}