From f5c4671bfbad96bf346bd7e9a21fc4317b4959df Mon Sep 17 00:00:00 2001 From: Indrajith K L Date: Sat, 3 Dec 2022 17:00:20 +0530 Subject: Adds most of the tools --- v_windows/v/examples/quick_sort.v | 42 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 v_windows/v/examples/quick_sort.v (limited to 'v_windows/v/examples/quick_sort.v') diff --git a/v_windows/v/examples/quick_sort.v b/v_windows/v/examples/quick_sort.v new file mode 100644 index 0000000..f890749 --- /dev/null +++ b/v_windows/v/examples/quick_sort.v @@ -0,0 +1,42 @@ +import rand + +const ( + gen_len = 1000 // how many random numbers to generate + gen_max = 10000 // max of the generated numbers +) + +fn main() { + mut arr := []int{} + for _ in 0 .. gen_len { + arr << rand.intn(gen_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(mut arr []T, 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++ + arr[i], arr[sep] = arr[sep], arr[i] + } + } + arr[l], arr[sep] = arr[sep], arr[l] + quick_sort(mut arr, l, sep - 1) + quick_sort(mut arr, sep + 1, r) +} + +fn is_sorted(arr []T) bool { + for i in 0 .. arr.len - 1 { + if arr[i] > arr[i + 1] { + return false + } + } + return true +} -- cgit v1.2.3