快速排序 Java 三种实现

超甜的布丁 2023-10-07 09:49:49 浏览数 (743)
反馈

快速排序(Quick Sort)是一种高效的排序算法,它基于分治策略,将一个大问题分解成多个小问题,然后递归解决这些小问题。本文将介绍快速排序算法的原理,并提供三种不同的 Java 实现方式,以帮助你更好地理解这个算法。

快速排序原理

快速排序的核心思想是选取一个基准元素,然后将数组中小于基准的元素移到基准的左边,大于基准的元素移到基准的右边。接着,对左右两个子数组分别递归地应用相同的算法,直到整个数组有序。

下面是快速排序的基本步骤:

  1. 选择一个基准元素(通常选择第一个或最后一个元素)。
  2. 将数组分成两个子数组:小于基准的元素和大于基准的元素。
  3. 递归地对子数组进行排序。
  4. 合并子数组和基准元素,得到最终排序后的数组。

第一种实现:使用递归

public class QuickSort {
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); } } public static int partition(int[] arr, int low, int high) { int pivot = arr[low]; int left = low + 1; int right = high; while (true) { while (left <= right && arr[left] < pivot) { left++; } while (left <= right && arr[right] > pivot) { right--; } if (left <= right) { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } else { break; } } int temp = arr[low]; arr[low] = arr[right]; arr[right] = temp; return right; } public static void main(String[] args) { int[] arr = {5, 2, 9, 3, 4, 6}; quickSort(arr, 0, arr.length - 1); System.out.println(Arrays.toString(arr)); } }

第二种实现:使用Stack

import java.util.Arrays;
import java.util.Stack; public class QuickSortUsingStack { public static void quickSort(int[] arr, int low, int high) { Stack<Integer> stack = new Stack<>(); stack.push(low); stack.push(high); while (!stack.isEmpty()) { high = stack.pop(); low = stack.pop(); int pivotIndex = partition(arr, low, high); if (pivotIndex - 1 > low) { stack.push(low); stack.push(pivotIndex - 1); } if (pivotIndex + 1 < high) { stack.push(pivotIndex + 1); stack.push(high); } } } public static int partition(int[] arr, int low, int high) { // 与第一种实现相同 } public static void main(String[] args) { int[] arr = {5, 2, 9, 3, 4, 6}; quickSort(arr, 0, arr.length - 1); System.out.println(Arrays.toString(arr)); } }

第三种实现:使用Lambdas

import java.util.Arrays;
import java.util.function.Predicate; public class QuickSortUsingLambdas { 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); } } public static int partition(int[] arr, int low, int high) { // 与第一种实现相同 } public static void main(String[] args) { int[] arr = {5, 2, 9, 3, 4, 6}; quickSort(arr, 0, arr.length - 1); System.out.println(Arrays.toString(arr)); } }

总结

快速排序是一种高效的排序算法,它的性能在平均情况下非常好。本文提供了三种不同的 Java 实现方式,包括递归、使用栈和使用Lambda表达式。你可以根据自己的需求选择合适的实现方式。

如果你想了解更多有关Java编程的知识,请访问编程狮官网。祝你编程愉快!


0 人点赞