From c26016b132cafcd1a2b4bfb8f2e8f59a32e7ea6e Mon Sep 17 00:00:00 2001 From: SleepyRoy <47302112+SleepyRoy@users.noreply.github.com> Date: Wed, 26 Feb 2020 20:32:39 +0800 Subject: [PATCH] examples: add quick_sort example --- examples/quick_sort.v | 50 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 examples/quick_sort.v diff --git a/examples/quick_sort.v b/examples/quick_sort.v new file mode 100644 index 0000000000..a9dfdbaead --- /dev/null +++ b/examples/quick_sort.v @@ -0,0 +1,50 @@ +import time +import rand + +const ( + LEN = 1000 // how many random numbers to generate + MAX = 10000 // max of the generated numbers +) + +fn main() { + rand.seed(time.now().unix) + rand.next(MAX) // skip the first + mut arr := []int + for _ in 0..LEN { + arr << rand.next(MAX) + } + println('length of random array is $arr.len') + println('before quick sort whether array is sorted: ${is_sorted(arr)}') + quick_sort(mut arr, 0, arr.len-1) + println('after quick sort whether array is sorted: ${is_sorted(arr)}') +} + +fn quick_sort(arr mut []int, l int, r int) { + if l>=r { return } + mut sep := l // what is sep: [...all_value=arr[sep]...] + for i in l+1..r+1 { + if arr[i] < arr[l] { + sep++ + swap(mut arr, i, sep) + } + } + swap(mut arr, l, sep) + quick_sort(mut arr, l, sep-1) + quick_sort(mut arr, sep+1, r) +} + +[inline] +fn swap(arr mut []int, i int, j int) { + temp := arr[i] + arr[i] = arr[j] + arr[j] = temp +} + +fn is_sorted(arr []int) bool { + for i in 0..arr.len-1 { + if arr[i] > arr[i+1] { + return false + } + } + return true +}