v/examples/quick_sort.v

41 lines
938 B
V
Raw Normal View History

import rand
const (
2020-05-22 17:36:09 +02:00
gen_len = 1000 // how many random numbers to generate
gen_max = 10000 // max of the generated numbers
)
fn main() {
2020-04-26 13:49:31 +02:00
mut arr := []int{}
2020-05-22 17:36:09 +02:00
for _ in 0..gen_len {
2020-06-09 15:06:07 +02:00
arr << rand.intn(gen_max)
}
println('length of random array is $arr.len')
println('before quick sort whether array is sorted: ${is_sorted<int>(arr)}')
quick_sort<int>(mut arr, 0, arr.len-1)
println('after quick sort whether array is sorted: ${is_sorted<int>(arr)}')
}
fn quick_sort<T>(mut arr []T, l int, r int) {
if l>=r { return }
mut sep := l // what is sep: [...all_value<arr[sep]...sep...all_value>=arr[sep]...]
for i in l+1..r+1 {
if arr[i] < arr[l] {
sep++
2020-07-02 13:32:02 +02:00
arr[i], arr[sep] = arr[sep], arr[i]
}
}
2020-07-02 13:32:02 +02:00
arr[l], arr[sep] = arr[sep], arr[l]
quick_sort<T>(mut arr, l, sep-1)
quick_sort<T>(mut arr, sep+1, r)
}
fn is_sorted<T>(arr []T) bool {
for i in 0..arr.len-1 {
if arr[i] > arr[i+1] {
return false
}
}
return true
}