快速排序(Quick Sort)是一种高效的排序算法,适用于各种应用场景。以下是一些常见的Java应用场景:
import java.util.Arrays;
public class QuickSortExample {
public static void main(String[] args) {
int[] arr = {3, 8, 2, 5, 1, 4, 7, 6};
quickSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
public static void quickSort(int[] arr, int low, int high) {
if (low< high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
private static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j< high; j++) {
if (arr[j] <= pivot) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return i + 1;
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class QuickSortListExample {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(3);
list.add(8);
list.add(2);
list.add(5);
list.add(1);
list.add(4);
list.add(7);
list.add(6);
Collections.sort(list); // 使用Java内置的排序方法,实际上也是快速排序
System.out.println(list);
}
}
Comparable
接口或者使用Comparator
接口。import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Person implements Comparable<Person> {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person other) {
return this.age - other.age;
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
public class QuickSortCustomObjectExample {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>();
persons.add(new Person("Alice", 30));
persons.add(new Person("Bob", 25));
persons.add(new Person("Charlie", 35));
Collections.sort(persons);
System.out.println(persons);
}
}
总之,快速排序在Java中的应用场景非常广泛,可以用于各种类型的数据排序。