1.递归的使用
package main
import (
"fmt"
"time"
)
func fibnum(i int) int{
if i==0{
return 0
}
if i==1{
return 1
}
fmt.Println("i is",i)
return fibnum(i-1)+fibnum(i-2)
}
func testthis(i int) {
if i==1{
fmt.Println("i is 1 ,out this")
return
}
if i==10{
fmt.Println("i is 10,out this")
return
}
fmt.Println("begin test; and i is now:",i)
time.Sleep(time.Second*1)
testthis(i-1)
fmt.Println("when i will be print??")
fmt.Println("i now is:",i)
testthis(i+1)
fmt.Println("test done, and i is now: ",i)
}
func main() {
fmt.Println(fibnum(3))
testthis(5)
}
使用递归快速排序
package main
import "fmt"
func quicksort(array []int, begin, end int, mark string) {
var i, j int
if begin < end {
i = begin + 1 // 将array[begin]作为基准数,因此从array[begin+1]开始与基准数比较!
j = end // array[end]是数组的最后一位
for {
if i >= j {
break
}
if array[i] > array[begin] {
array[i], array[j] = array[j], array[i]
j = j - 1
} else {
i = i + 1 //此处放在else内,很重要,二分思想!
}
}
//fmt.Println("array and i and j is",array,i,j)
if array[i] >= array[begin] {
i = i - 1
}
array[begin], array[i] = array[i], array[begin]
//fmt.Printf("%s>sort:%v\n", mark, array[begin:end])
fmt.Println("array and i and j is",array,i,j)
fmt.Printf("%s>%v,%d,%v\n", mark, array[begin:i], array[i], array[j:]) //后标取不到
quicksort(array, begin, i, mark+"--")
quicksort(array, j, end, mark+"--")
}
}
func main() {
nums := []int{12, 85, 25, 16, 34, 23, 49, 95, 17, 61}
fmt.Printf("begin:%#v\n", nums)
mark := "--"
quicksort(nums, 0, len(nums)-1, mark)
fmt.Printf("last:%#v\n", nums)
}
2.关于递归上下文的测试
package main
import (
"fmt"
)
var i int = 0
func testagain(step int){
if step==5{
//fmt.Println(a)
return
}
fmt.Println("begin i is:",i)
i++
testagain(step+1)
fmt.Println("after i is",i)
i--
return
}
func main(){
testagain(1)
}
运行的结果如下:
begin i is: 0
begin i is: 1
begin i is: 2
begin i is: 3
after i is 4
after i is 3
after i is 2
after i is 1