add textbook method code

use code from textbook, add some trick to shrink the brk