Fast algorithm implementation to sort very small list

后端 未结 6 1727
予麋鹿
予麋鹿 2020-11-28 08:42

This is the problem I ran into long time ago. I thought I may ask your for your ideas. assume I have very small list of numbers (integers), 4 or 8 elements, that need to be

6条回答
  •  生来不讨喜
    2020-11-28 08:56

    To sort small amounts of numbers you want a simple algorithm as complexity adds more overhead.

    The most efficient way to sort for example four items would be to unravel the sorting algorithm to linear comparisons, thus elliminating all overhead:

    function sort(i,j,k,l) {
      if (i < j) {
        if (j < k) {
          if (k < l) return [i,j,k,l];
          if (j < l) return [i,j,l,k];
          if (i < l) return [i,l,j,k];
          return [l,i,j,k];
        } else if (i < k) {
          if (j < l) return [i,k,j,l];
          if (k < l) return [i,k,l,j];
          if (i < l) return [i,l,k,j];
          return [l,i,k,j];
        } else {
          if (j < l) return [k,i,j,l];
          if (i < l) return [k,i,l,j];
          if (k < l) return [k,l,i,j];
          return [l,k,i,j];
        }
      } else {
        if (i < k) {
          if (k < l) return [j,i,k,l];
          if (i < l) return [j,i,l,k];
          if (j < l) return [j,l,i,k];
          return [l,j,i,k];
        } else if (j < k) {
          if (i < l) return [j,k,i,l];
          if (k < l) return [j,k,l,i];
          if (j < l) return [j,l,k,i];
          return [l,j,k,i];
        } else {
          if (i < l) return [k,j,i,l];
          if (j < l) return [k,j,l,i];
          if (k < l) return [k,l,j,i];
          return [l,k,j,i];
        }
      }
    }
    

    However, the code grows a lot for each extra item you add. Adding a fifth item makes the code roughly four times larger. At eight items it would be roughly 30000 lines, so although it's still the most efficient, it's a lot of code, and you would have to write a program that writes the code to get it correct.

提交回复
热议问题