1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00
v/examples/quick_sort.v

50 lines
1.0 KiB
V
Raw Normal View History

import time
import rand
const (
2020-05-22 18:36:09 +03:00
gen_len = 1000 // how many random numbers to generate
gen_max = 10000 // max of the generated numbers
)
fn main() {
2020-06-09 16:06:07 +03:00
rand.intn(gen_max) // skip the first
2020-04-26 14:49:31 +03:00
mut arr := []int{}
2020-05-22 18:36:09 +03:00
for _ in 0..gen_len {
2020-06-09 16:06:07 +03:00
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)}')
}
2020-06-04 11:35:40 +03:00
fn quick_sort(mut arr []int, 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++
swap(mut arr, i, sep)
}
}
swap(mut arr, l, sep)
quick_sort(mut arr, l, sep-1)
quick_sort(mut arr, sep+1, r)
}
2020-04-26 14:49:31 +03:00
[inline]
2020-06-04 11:35:40 +03:00
fn swap(mut arr []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
}