免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
楼主: 无风之谷
打印 上一主题 下一主题

让我欢喜让我忧——我的C++之路 [复制链接]

论坛徽章:
2
青铜圣斗士
日期:2015-11-26 06:15:59数据库技术版块每日发帖之星
日期:2016-07-24 06:20:00
591 [报告]
发表于 2012-04-18 18:08 |只看该作者
hellioncu 发表于 2012-04-18 17:26
结果正确,不表明代码没错误,这道理你应该懂。


关于"应该"这点,你太想当然了
这道理很多人都不懂,凭什么要求作者懂

论坛徽章:
0
592 [报告]
发表于 2012-04-18 18:27 |只看该作者
hellioncu 发表于 2012-04-18 17:26
不知道说你什么好,错了还不肯承认。

结果正确,不表明代码没错误,这道理你应该懂。


我不是不承认阿,我不是根据函数的说明对代码作了修改了吗?

可是我不明白的是,
结果正确,不表明代码没错误
那么既然代码有错误,结果又怎么会正确呢?

又或者可以说,虽然结果正确,但是损失了效率,代码有瑕疵?

我就是这一点没有搞明白,所以向大家请教啊

论坛徽章:
2
青铜圣斗士
日期:2015-11-26 06:15:59数据库技术版块每日发帖之星
日期:2016-07-24 06:20:00
593 [报告]
发表于 2012-04-18 18:42 |只看该作者
陈良乔 发表于 2012-04-18 18:27
我不是不承认阿,我不是根据函数的说明对代码作了修改了吗?

可是我不明白的是,
结果正确,不表明代码没错误
那么既然代码有错误,结果又怎么会正确呢?

又或者可以说,虽然结果正确,但是损失了效率,代码有瑕疵?

我就是这一点没有搞明白,所以向大家请教啊


果不其然


作为面向初学者的作者,要传授的是:不要闯红灯。
而不是:大家跟我学闯红灯,因为这里没有监视器。

论坛徽章:
0
594 [报告]
发表于 2012-04-18 19:36 |只看该作者
呵呵,傻

论坛徽章:
0
595 [报告]
发表于 2012-04-18 19:45 |只看该作者
本帖最后由 AD8018 于 2012-04-18 19:48 编辑

现在找不到反例,不代表没有,更不代表未来没有。

造反例还不简单,比如,写一个debug版本的qsort,
它里面有验证动作,排完序后,再调用cmp函数验证两遍,
  从头到尾验证一遍,是否满足<=
  从尾到头再验证一遍,是否满足 >=
如不满足直接报错。
(这个qsort完全满足标准,因而是合法的。)

C++专家的cmp函数,是无法拿来做验证的。

论坛徽章:
324
射手座
日期:2013-08-23 12:04:38射手座
日期:2013-08-23 16:18:12未羊
日期:2013-08-30 14:33:15水瓶座
日期:2013-09-02 16:44:31摩羯座
日期:2013-09-25 09:33:52双子座
日期:2013-09-26 12:21:10金牛座
日期:2013-10-14 09:08:49申猴
日期:2013-10-16 13:09:43子鼠
日期:2013-10-17 23:23:19射手座
日期:2013-10-18 13:00:27金牛座
日期:2013-10-18 15:47:57午马
日期:2013-10-18 21:43:38
596 [报告]
发表于 2012-04-18 19:51 |只看该作者
OwnWaterloo 发表于 2012-04-18 18:08
关于"应该"这点,你太想当然了
这道理很多人都不懂,凭什么要求作者懂


我本以为能写书出版的人,这点认识应该有的。我也以为既然敢白纸黑字印刷出来的,也能敢于承认错误的。

论坛徽章:
324
射手座
日期:2013-08-23 12:04:38射手座
日期:2013-08-23 16:18:12未羊
日期:2013-08-30 14:33:15水瓶座
日期:2013-09-02 16:44:31摩羯座
日期:2013-09-25 09:33:52双子座
日期:2013-09-26 12:21:10金牛座
日期:2013-10-14 09:08:49申猴
日期:2013-10-16 13:09:43子鼠
日期:2013-10-17 23:23:19射手座
日期:2013-10-18 13:00:27金牛座
日期:2013-10-18 15:47:57午马
日期:2013-10-18 21:43:38
597 [报告]
发表于 2012-04-18 19:57 |只看该作者
本帖最后由 hellioncu 于 2012-04-18 19:57 编辑
陈良乔 发表于 2012-04-18 18:27
我不是不承认阿,我不是根据函数的说明对代码作了修改了吗?

可是我不明白的是,


最后说一句,如果你还要写书,想要好的名声,那么请认真点。如果你是真不懂,那还是别再写书出丑了。

论坛徽章:
0
598 [报告]
发表于 2012-04-18 20:12 |只看该作者
本帖最后由 AD8018 于 2012-04-19 13:15 编辑

再为失足男女开个光,看看新的debug版本的my_qsort,
如果cmp不考虑相等,会有什么反应。

  1. int cmp(const void *a, const void *b)
  2. {
  3.         const float *fa = (const float *)a;
  4.         const float *fb = (const float *)b;
  5.        
  6.         if(*fa < *fb) return -1;
  7.         else return 1;  //注意:错误
  8. }
复制代码
开光版my_qsort


  1. /* Copyright (C) 1991,1992,1996,1997,1999,2004 Free Software Foundation, Inc.
  2.    This file is part of the GNU C Library.
  3.    Written by Douglas C. Schmidt (schmidt@ics.uci.edu).

  4.    The GNU C Library is free software; you can redistribute it and/or
  5.    modify it under the terms of the GNU Lesser General Public
  6.    License as published by the Free Software Foundation; either
  7.    version 2.1 of the License, or (at your option) any later version.

  8.    The GNU C Library is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  11.    Lesser General Public License for more details.

  12.    You should have received a copy of the GNU Lesser General Public
  13.    License along with the GNU C Library; if not, write to the Free
  14.    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  15.    02111-1307 USA.  */

  16. /* If you consider tuning this algorithm, you should consult first:
  17.    Engineering a sort function; Jon Bentley and M. Douglas McIlroy;
  18.    Software - Practice and Experience; Vol. 23 (11), 1249-1265, 1993.  */

  19. #include <assert.h>
  20. #include <limits.h>
  21. #include <stdlib.h>
  22. #include <string.h>

  23. /* Byte-wise swap two items of size SIZE. */
  24. #define SWAP(a, b, size)                                                      \
  25.   do                                                                              \
  26.     {                                                                              \
  27.       register size_t __size = (size);                                              \
  28.       register char *__a = (a), *__b = (b);                                      \
  29.       do                                                                      \
  30.         {                                                                      \
  31.           char __tmp = *__a;                                                      \
  32.           *__a++ = *__b;                                                      \
  33.           *__b++ = __tmp;                                                      \
  34.         } while (--__size > 0);                                                      \
  35.     } while (0)

  36. /* Discontinue quicksort algorithm when partition gets below this size.
  37.    This particular magic number was chosen to work best on a Sun 4/260. */
  38. #define MAX_THRESH 4

  39. /* Stack node declarations used to store unfulfilled partition obligations. */
  40. typedef struct
  41.   {
  42.     char *lo;
  43.     char *hi;
  44.   } stack_node;

  45. /* The next 4 #defines implement a very fast in-line stack abstraction. */
  46. /* The stack needs log (total_elements) entries (we could even subtract
  47.    log(MAX_THRESH)).  Since total_elements has type size_t, we get as
  48.    upper bound for log (total_elements):
  49.    bits per byte (CHAR_BIT) * sizeof(size_t).  */
  50. #define STACK_SIZE        (CHAR_BIT * sizeof(size_t))
  51. #define PUSH(low, high)        ((void) ((top->lo = (low)), (top->hi = (high)), ++top))
  52. #define        POP(low, high)        ((void) (--top, (low = top->lo), (high = top->hi)))
  53. #define        STACK_NOT_EMPTY        (stack < top)


  54. /* Order size using quicksort.  This implementation incorporates
  55.    four optimizations discussed in Sedgewick:

  56.    1. Non-recursive, using an explicit stack of pointer that store the
  57.       next array partition to sort.  To save time, this maximum amount
  58.       of space required to store an array of SIZE_MAX is allocated on the
  59.       stack.  Assuming a 32-bit (64 bit) integer for size_t, this needs
  60.       only 32 * sizeof(stack_node) == 256 bytes (for 64 bit: 1024 bytes).
  61.       Pretty cheap, actually.

  62.    2. Chose the pivot element using a median-of-three decision tree.
  63.       This reduces the probability of selecting a bad pivot value and
  64.       eliminates certain extraneous comparisons.

  65.    3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
  66.       insertion sort to order the MAX_THRESH items within each partition.
  67.       This is a big win, since insertion sort is faster for small, mostly
  68.       sorted array segments.

  69.    4. The larger of the two sub-partitions is always pushed onto the
  70.       stack first, with the algorithm then concentrating on the
  71.       smaller partition.  This *guarantees* no more than log (total_elems)
  72.       stack size is needed (actually O(1) in this case)!  */

  73. void
  74. _quicksort (void *const pbase, size_t total_elems, size_t size,
  75.         int (*cmp)(const void *, const void *))
  76. {
  77.   register char *base_ptr = (char *) pbase;

  78.   const size_t max_thresh = MAX_THRESH * size;

  79.   if (total_elems == 0)
  80.     /* Avoid lossage with unsigned arithmetic below.  */
  81.     return;

  82.   if (total_elems > MAX_THRESH)
  83.     {
  84.       char *lo = base_ptr;
  85.       char *hi = &lo[size * (total_elems - 1)];
  86.       stack_node stack[STACK_SIZE];
  87.       stack_node *top = stack;

  88.       PUSH (NULL, NULL);

  89.       while (STACK_NOT_EMPTY)
  90.         {
  91.           char *left_ptr;
  92.           char *right_ptr;

  93.           /* Select median value from among LO, MID, and HI. Rearrange
  94.              LO and HI so the three values are sorted. This lowers the
  95.              probability of picking a pathological pivot value and
  96.              skips a comparison for both the LEFT_PTR and RIGHT_PTR in
  97.              the while loops. */

  98.           char *mid = lo + size * ((hi - lo) / size >> 1);

  99.           if ((*cmp) ((void *) mid, (void *) lo) < 0)
  100.             SWAP (mid, lo, size);
  101.           if ((*cmp) ((void *) hi, (void *) mid) < 0)
  102.             SWAP (mid, hi, size);
  103.           else
  104.             goto jump_over;
  105.           if ((*cmp) ((void *) mid, (void *) lo) < 0)
  106.             SWAP (mid, lo, size);
  107.         jump_over:;

  108.           left_ptr  = lo + size;
  109.           right_ptr = hi - size;

  110.           /* Here's the famous ``collapse the walls'' section of quicksort.
  111.              Gotta like those tight inner loops!  They are the main reason
  112.              that this algorithm runs much faster than others. */
  113.           do
  114.             {
  115.               while ((*cmp) ((void *) left_ptr, (void *) mid) < 0)
  116.                 left_ptr += size;

  117.               while ((*cmp) ((void *) mid, (void *) right_ptr) < 0)
  118.                 right_ptr -= size;

  119.               if (left_ptr < right_ptr)
  120.                 {
  121.                   SWAP (left_ptr, right_ptr, size);
  122.                   if (mid == left_ptr)
  123.                     mid = right_ptr;
  124.                   else if (mid == right_ptr)
  125.                     mid = left_ptr;
  126.                   left_ptr += size;
  127.                   right_ptr -= size;
  128.                 }
  129.               else if (left_ptr == right_ptr)
  130.                 {
  131.                   left_ptr += size;
  132.                   right_ptr -= size;
  133.                   break;
  134.                 }
  135.             }
  136.           while (left_ptr <= right_ptr);

  137.           /* Set up pointers for next iteration.  First determine whether
  138.              left and right partitions are below the threshold size.  If so,
  139.              ignore one or both.  Otherwise, push the larger partition's
  140.              bounds on the stack and continue sorting the smaller one. */

  141.           if ((size_t) (right_ptr - lo) <= max_thresh)
  142.             {
  143.               if ((size_t) (hi - left_ptr) <= max_thresh)
  144.                 /* Ignore both small partitions. */
  145.                 POP (lo, hi);
  146.               else
  147.                 /* Ignore small left partition. */
  148.                 lo = left_ptr;
  149.             }
  150.           else if ((size_t) (hi - left_ptr) <= max_thresh)
  151.             /* Ignore small right partition. */
  152.             hi = right_ptr;
  153.           else if ((right_ptr - lo) > (hi - left_ptr))
  154.             {
  155.               /* Push larger left partition indices. */
  156.               PUSH (lo, right_ptr);
  157.               lo = left_ptr;
  158.             }
  159.           else
  160.             {
  161.               /* Push larger right partition indices. */
  162.               PUSH (left_ptr, hi);
  163.               hi = right_ptr;
  164.             }
  165.         }
  166.     }

  167.   /* Once the BASE_PTR array is partially sorted by quicksort the rest
  168.      is completely sorted using insertion sort, since this is efficient
  169.      for partitions below MAX_THRESH size. BASE_PTR points to the beginning
  170.      of the array to sort, and END_PTR points at the very last element in
  171.      the array (*not* one beyond it!). */

  172. #define min(x, y) ((x) < (y) ? (x) : (y))

  173.   {
  174.     char *const end_ptr = &base_ptr[size * (total_elems - 1)];
  175.     char *tmp_ptr = base_ptr;
  176.     char *thresh = min(end_ptr, base_ptr + max_thresh);
  177.     register char *run_ptr;

  178.     /* Find smallest element in first threshold and place it at the
  179.        array's beginning.  This is the smallest array element,
  180.        and the operation speeds up insertion sort's inner loop. */

  181.     for (run_ptr = tmp_ptr + size; run_ptr <= thresh; run_ptr += size)
  182.       if ((*cmp) ((void *) run_ptr, (void *) tmp_ptr) < 0)
  183.         tmp_ptr = run_ptr;

  184.     if (tmp_ptr != base_ptr)
  185.       SWAP (tmp_ptr, base_ptr, size);

  186.     /* Insertion sort, running from left-hand-side up to right-hand-side.  */

  187.     run_ptr = base_ptr + size;
  188.     while ((run_ptr += size) <= end_ptr)
  189.       {
  190.         tmp_ptr = run_ptr - size;
  191.         while ((*cmp) ((void *) run_ptr, (void *) tmp_ptr) < 0)
  192.           tmp_ptr -= size;

  193.         tmp_ptr += size;
  194.         if (tmp_ptr != run_ptr)
  195.           {
  196.             char *trav;

  197.             trav = run_ptr + size;
  198.             while (--trav >= run_ptr)
  199.               {
  200.                 char c = *trav;
  201.                 char *hi, *lo;

  202.                 for (hi = lo = trav; (lo -= size) >= tmp_ptr; hi = lo)
  203.                   *hi = *lo;
  204.                 *hi = c;
  205.               }
  206.           }
  207.       }
  208.   }
  209. }


  210. void my_qsort(void *base, size_t nel, size_t width,
  211.          int (*compar)(const void *, const void *))
  212. {
  213.         _quicksort(base, nel, width, compar);
  214.        
  215. #ifndef NDEBUG
  216.         /* Verify */
  217.         {
  218.                 size_t i;
  219.                 const char *prev = (const char *)base;
  220.                 for(i = 1; i < nel; ++i)
  221.                 {
  222.                         assert((*compar)(prev, prev + width) <= 0);
  223.                         assert((*compar)(prev + width, prev) >= 0);
  224.                         prev += width;
  225.                 }
  226.         }
  227. #endif
  228. }

  229. int cmp(const void *a, const void *b)
  230. {
  231.         const float *fa = (const float *)a;
  232.         const float *fb = (const float *)b;
  233.        
  234.         if(*fa < *fb) return -1;
  235.         if(*fa > *fb) return 1;
  236.         else return 0;
  237. }

  238. int main()
  239. {
  240.         float arr[] = {11, 22, 11, 12, 13, 22};
  241.         size_t i;
  242.        
  243.         my_qsort(arr, sizeof(arr) / sizeof(arr[0]), sizeof(arr[0]), cmp);
  244.        
  245.         for(i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i)
  246.                 printf("%f ", arr[i]);
  247.         return 0;
  248. }

复制代码

论坛徽章:
2
程序设计版块每日发帖之星
日期:2015-06-17 22:20:00每日论坛发贴之星
日期:2015-06-17 22:20:00
599 [报告]
发表于 2012-04-18 21:04 |只看该作者
提示: 作者被禁止或删除 内容自动屏蔽

论坛徽章:
2
程序设计版块每日发帖之星
日期:2015-06-17 22:20:00每日论坛发贴之星
日期:2015-06-17 22:20:00
600 [报告]
发表于 2012-04-18 21:05 |只看该作者
提示: 作者被禁止或删除 内容自动屏蔽
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP