#pragma once #include <iostream> #include <random> #include <algorithm> using namespace std; random_device rd; mt19937_64 mt(rd()); template<typename T> T getRandom(T min, T max) { uniform_int_distribution<T> uid(min, max); return uid(mt); } template<typename T> void swap(T* left, T* right) { if (*left == *right) { return; } T temp = *left; *left = *right; *right = temp; } template<typename T> int partitionAsc(T* arr, int low, int high) { T pivot = arr[high]; int i = low - 1; for (int j = low; j < high; j++) { if (arr[j] < pivot) { i = i + 1; swap<T>(&arr[i], &arr[j]); } } swap<T>(&arr[i+1], &arr[high]); return i + 1; } template<typename T> void quickSort(T* arr, int low, int high) { if (low < high) { int pivot = partitionAsc(arr, low, high); quickSort(arr, low, pivot - 1); quickSort(arr, pivot + 1, high); } } void arrayDemo(int len) { uint32_t * arr = new uint32_t[len]; for (int i = 0; i < len; i++) { arr[i] = getRandom<uint32_t>(0, UINT32_MAX); } cout << "Before quick sort:" << endl; for (int i = 0; i < len; i++) { cout << arr[i] << "\t"; } cout << endl << endl; cout << "After quick sort:" << endl; quickSort<uint32_t>(arr, 0, len - 1); for (int i = 0; i < len; i++) { cout << arr[i] << "\t"; } cout << endl << endl; delete[]arr; } int main() { arrayDemo(1000); }
标签:sort,arr,int,high,low,template,quick,pivot,generate From: https://www.cnblogs.com/Fred1987/p/16790957.html