Sorting an array with minimal number of comparisons

前端 未结 6 1267
情话喂你
情话喂你 2020-11-29 06:09

I need some help with my CS homework. I need to write a sorting routine that sorts an array of length 5 using 7 comparisons in the worst case (I\'ve proven that 7 will be ne

6条回答
  •  再見小時候
    2020-11-29 06:24

    Yes it is in Knuth vol 3 page 185 (section 5.3.1). This was first documented in a PhD thesis so your Prof is being quite hard on you! There is no really simple elegant method; you have to track it as a partially ordered tree.

    Here it is in lisp. Tested OK (SBCL on Linux)

    (defun small-sort (a)  
      "Sort a vector A of length 5"  
      (if (> (aref a 0) (aref a 1))  
          (rotatef (aref a 0) (aref a 1)))  
      (if (> (aref a 2) (aref a 3))  
          (rotatef (aref a 2) (aref a 3)))  
      (if (> (aref a 0) (aref a 2))  
          (progn  
            (rotatef (aref a 0) (aref a 2))  
            (rotatef (aref a 1) (aref a 3))))  
      (if (> (aref a 4) (aref a 2))  
          (if (> (aref a 4) (aref a 3))  
              (progn)  
              (rotatef (aref a 3) (aref a 4)))  
          (if (> (aref a 4) (aref a 0))  
              (rotatef (aref a 2) (aref a 4) (aref a 3))  
              (rotatef (aref a 0) (aref a 4) (aref a 3) (aref a 2))))  
      (if (> (aref a 1) (aref a 3))  
          (if (> (aref a 1) (aref a 4))  
              (rotatef (aref a 1) (aref a 2) (aref a 3) (aref a 4))  
              (rotatef (aref a 1) (aref a 2) (aref a 3)))  
          (if (> (aref a 1) (aref a 2))  
              (rotatef (aref a 1) (aref a 2))  
              (progn)))  
      a)  
    
    (defun check-sorted (a)  
      (do ((i 0 (1+ i)))  
          ((>= i (1- (array-dimension a 0))))  
        ;;(format t "~S ~S~%" (aref a i) (aref a (+ 1 i)))  
        (assert (<= (aref a i) (aref a (+ 1 i))))))  
    
    (defun rr ()  
      (dotimes (i 100000)  
        (let ((a (make-array 5 :initial-contents (list (random 1.0) (random 1.0) (random 1.0) (random 1.0) (random 1.0) ))))  
          ;;(format t "A=~S~%" a)  
          (let ((res (small-sort a)))  
            (check-sorted res)  
            ;;(format t "Res=~S~%" res)  
            ))))  
    

提交回复
热议问题