快排
#include <vector> #include <iostream> using namespace std; void quickSort(int* array, int start, int end) { if (start >= end) { return; } int i = start, j = end; int available = i; int pivot = array[start]; while (i < j) { while (array[j] >= pivot && i < j) { j--; }; if (i < j) { array[available] = array[j]; available = j; } while (array[i] <= pivot && i < j) { i++; } if (i < j) { array[available] = array[i]; available = i; } } array[available] = pivot; quickSort(array, start, available - 1); quickSort(array, available + 1, end); } int main(void) { int array[] = {4,3,5,2,7,9}; quickSort(array,0,5); for (int i = 0;i <= 5;i++) { cout << array[i] << " "; } system("pause"); }
package main import "fmt" func quickSort(a []int) { l := len(a) if l < 2 { return } i := 0 j := l - 1 pivot := a[i] for i < j { for i < j && a[j] >= pivot { j-- } for i < j && a[i] <= pivot { i++ } if (i < j ) { tmp := a[j] a[j] = a[i] a[i] = tmp } } tmp := a[i] a[i] = pivot a[0] = tmp quickSort(a[0:i]) quickSort(a[i + 1:l]) } func main() { a := []int{6, 5, 2, 7, 3, 9, 8, 4, 10, 1} quickSort(a) fmt.Println(a) }
作者:严彦彪
原创作品转载请注明出处