example: make quick_sort generic (#5898)
parent
a74cbf55c7
commit
53e7cb124d
|
@ -11,12 +11,12 @@ fn main() {
|
||||||
arr << rand.intn(gen_max)
|
arr << rand.intn(gen_max)
|
||||||
}
|
}
|
||||||
println('length of random array is $arr.len')
|
println('length of random array is $arr.len')
|
||||||
println('before quick sort whether array is sorted: ${is_sorted(arr)}')
|
println('before quick sort whether array is sorted: ${is_sorted<int>(arr)}')
|
||||||
quick_sort(mut arr, 0, arr.len-1)
|
quick_sort<int>(mut arr, 0, arr.len-1)
|
||||||
println('after quick sort whether array is sorted: ${is_sorted(arr)}')
|
println('after quick sort whether array is sorted: ${is_sorted<int>(arr)}')
|
||||||
}
|
}
|
||||||
|
|
||||||
fn quick_sort(mut arr []int, l int, r int) {
|
fn quick_sort<T>(mut arr []T, l int, r int) {
|
||||||
if l>=r { return }
|
if l>=r { return }
|
||||||
mut sep := l // what is sep: [...all_value<arr[sep]...sep...all_value>=arr[sep]...]
|
mut sep := l // what is sep: [...all_value<arr[sep]...sep...all_value>=arr[sep]...]
|
||||||
for i in l+1..r+1 {
|
for i in l+1..r+1 {
|
||||||
|
@ -26,11 +26,11 @@ fn quick_sort(mut arr []int, l int, r int) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
arr[l], arr[sep] = arr[sep], arr[l]
|
arr[l], arr[sep] = arr[sep], arr[l]
|
||||||
quick_sort(mut arr, l, sep-1)
|
quick_sort<T>(mut arr, l, sep-1)
|
||||||
quick_sort(mut arr, sep+1, r)
|
quick_sort<T>(mut arr, sep+1, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_sorted(arr []int) bool {
|
fn is_sorted<T>(arr []T) bool {
|
||||||
for i in 0..arr.len-1 {
|
for i in 0..arr.len-1 {
|
||||||
if arr[i] > arr[i+1] {
|
if arr[i] > arr[i+1] {
|
||||||
return false
|
return false
|
||||||
|
|
Loading…
Reference in New Issue