运行 ❯
获取您
自己的
网站
×
更改方向
更改主题,深色/浅色
前往 Spaces
Python
C
Java
def partition(array, low, high): pivot = array[high] i = low - 1 for j in range(low, high): if array[j] <= pivot: i += 1 array[i], array[j] = array[j], array[i] array[i+1], array[high] = array[high], array[i+1] return i+1 def quicksort(array, low=0, high=None): if high is None: high = len(array) - 1 if low < high: pivot_index = partition(array, low, high) quicksort(array, low, pivot_index-1) quicksort(array, pivot_index+1, high) my_array = [64, 34, 25, 12, 22, 11, 90, 5] quicksort(my_array) print("Sorted array:", my_array) #Python
#include <stdio.h> void quicksort(int array[], int low, int high); int partition(int array[], int low, int high); int main() { int myArray[] = {64, 34, 25, 12, 22, 11, 90, 5}; int n = sizeof(myArray) / sizeof(myArray[0]); quicksort(myArray, 0, n - 1); printf("Sorted array: "); for (int i = 0; i < n; i++) { printf("%d ", myArray[i]); } return 0; } void quicksort(int array[], int low, int high) { if (low < high) { int pivotIndex = partition(array, low, high); quicksort(array, low, pivotIndex - 1); quicksort(array, pivotIndex + 1, high); } } int partition(int array[], int low, int high) { int pivot = array[high]; int i = low - 1; for (int j = low; j < high; j++) { if (array[j] <= pivot) { i++; int temp = array[i]; array[i] = array[j]; array[j] = temp; } } int temp = array[i + 1]; array[i + 1] = array[high]; array[high] = temp; return i + 1; } //C
public class Main { public static void main(String[] args) { int[] myArray = {64, 34, 25, 12, 22, 11, 90, 5}; quicksort(myArray, 0, myArray.length - 1); System.out.print("Sorted array: "); for (int value : myArray) { System.out.print(value + " "); } } public static void quicksort(int[] array, int low, int high) { if (low < high) { int pivotIndex = partition(array, low, high); quicksort(array, low, pivotIndex - 1); quicksort(array, pivotIndex + 1, high); } } public static int partition(int[] array, int low, int high) { int pivot = array[high]; int i = low - 1; for (int j = low; j < high; j++) { if (array[j] <= pivot) { i++; int temp = array[i]; array[i] = array[j]; array[j] = temp; } } int temp = array[i + 1]; array[i + 1] = array[high]; array[high] = temp; return i + 1; } } //Java
Python 结果
C 结果
Java 结果
排序后的数组: [5, 11, 12, 22, 25, 34, 64, 90]
排序后的数组: 5 11 12 22 25 34 64 90
排序后的数组: 5 11 12 22 25 34 64 90