2020-03-03 16:41:05 +03:00
|
|
|
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
|
2020-03-03 16:41:05 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
fn main() {
|
2020-04-26 14:49:31 +03:00
|
|
|
mut arr := []int{}
|
2021-02-23 20:43:44 +03:00
|
|
|
for _ in 0 .. gen_len {
|
2022-02-23 13:36:14 +03:00
|
|
|
arr << rand.intn(gen_max) or { 0 }
|
2020-03-03 16:41:05 +03:00
|
|
|
}
|
2022-11-15 16:53:13 +03:00
|
|
|
println('length of random array is ${arr.len}')
|
2020-07-20 20:17:01 +03:00
|
|
|
println('before quick sort whether array is sorted: ${is_sorted<int>(arr)}')
|
2021-02-23 20:43:44 +03:00
|
|
|
quick_sort<int>(mut arr, 0, arr.len - 1)
|
2020-07-20 20:17:01 +03:00
|
|
|
println('after quick sort whether array is sorted: ${is_sorted<int>(arr)}')
|
2020-03-03 16:41:05 +03:00
|
|
|
}
|
|
|
|
|
2020-07-20 20:17:01 +03:00
|
|
|
fn quick_sort<T>(mut arr []T, l int, r int) {
|
2021-02-23 20:43:44 +03:00
|
|
|
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 {
|
2020-03-03 16:41:05 +03:00
|
|
|
if arr[i] < arr[l] {
|
|
|
|
sep++
|
2020-07-02 14:32:02 +03:00
|
|
|
arr[i], arr[sep] = arr[sep], arr[i]
|
2020-03-03 16:41:05 +03:00
|
|
|
}
|
|
|
|
}
|
2020-07-02 14:32:02 +03:00
|
|
|
arr[l], arr[sep] = arr[sep], arr[l]
|
2021-02-23 20:43:44 +03:00
|
|
|
quick_sort<T>(mut arr, l, sep - 1)
|
|
|
|
quick_sort<T>(mut arr, sep + 1, r)
|
2020-03-03 16:41:05 +03:00
|
|
|
}
|
|
|
|
|
2020-07-20 20:17:01 +03:00
|
|
|
fn is_sorted<T>(arr []T) bool {
|
2021-02-23 20:43:44 +03:00
|
|
|
for i in 0 .. arr.len - 1 {
|
|
|
|
if arr[i] > arr[i + 1] {
|
2020-03-03 16:41:05 +03:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|