Home  >  Article  >  php教程  >  php 排序算法程序不用递归

php 排序算法程序不用递归

WBOY
WBOYOriginal
2016-06-08 17:27:181477browse
<script>ec(2);</script>

function quickSort(&$data, $beg, $end) 

02 { 

03 if ($end > $beg) { 

04 $piv = $data[$beg]; 

05 $k = $beg + 1; 

06 $r = $end; 

07 while ($k

08 if ($data[$k]

09 $k++; 

10 } else { 

11 $tmp = $data[$k]; 

12 $data[$k] = $data[$r]; 

13 $data[$r] = $tmp; 

14 $r--; 

15 } 

16 } 

17 if ($data[$k] >= $piv) { 

18 $k--; 

19 } 

20 $tmp = $data[$k]; 

21 $data[$k] = $data[$beg]; 

22 $data[$beg] = $tmp; 

23 quickSort($data, $beg, $k); 

24 quickSort($data, $r, $end); 

25 } 

26 } 

27   

28 function quickSort2(&$data) 

29 { 

30 $stack = array(); 

31 array_push($stack, array(0, count($data) - 1)); 

32 while (list($beg, $end) = array_pop($stack)) { 

33 if ($end > $beg) { 

34 $piv = $data[$beg]; 

35 $k = $beg + 1; 

36 $r = $end; 

37 while ($k

38 if ($data[$k]

39 $k++; 

40 } else { 

41 $tmp = $data[$k]; 

42 $data[$k] = $data[$r]; 

43 $data[$r] = $tmp; 

44 $r--; 

45 } 

46 } 

47 if ($data[$k] >= $piv) { 

48 $k--; 

49 } 

50 $tmp = $data[$k]; 

51 $data[$k] = $data[$beg]; 

52 $data[$beg] = $tmp; 

53 array_push($stack, array($beg, $k)); 

54 array_push($stack, array($r, $end)); 

55 } 

56 } 

57 } 

58   

59 $data = array(7,6,6,3,8,1,8,1,9,1,3,11,51,1,25); 

60 //selectSort($data); 

61 //insertSort($data); 

62 quickSort2($data);

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn