【问题标题】:looking for a sorting algorithm that can sort 1-100 using the least amount of statements寻找一种可以使用最少的语句对 1-100 进行排序的排序算法
【发布时间】:2019-01-21 13:18:57
【问题描述】:

正如标题所说,我正在寻找一种排序算法,它可以仅在一种主要方法中使用最少的语句对 1 到 100 之间的数字进行排序。 这是一个示例,可让您了解如何检查它(使用计数器)

class Solution{
public static void main(String[] args) {   

  //declaration
  int count = 0,inner, outer, temp, h = 1; count++;
  int [] array = {100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,}; count++;
  System.out.println("Before: " + Arrays.toString(array)); count++;


  //start of the sort
  while (h <= array.length / 3) //start of while loop 1
    {
    h = h * 3 + 1; count++;
    }count++; //end of while loop 1
    while (h > 0) //start of while loop 2
    {
        for (outer = h; outer < array.length; outer++) //start of for loop
        {
            temp = array[outer]; count++;
            inner = outer;count++;

            while (inner > h - 1 && array[inner - h] >= temp) //start of while loop 3
            {
                array[inner] = array[inner - h]; count++;
                inner -= h; count++;
            }count++; //end of for loop 3
            array[inner] = temp; count++;
        }count++; //end of for loop
        //equation to count for
        count = count + array.length-h+1 + array.length - h +1 -1;
        h = (h - 1) / 3; count++;
    }count++; //end of while loop 2
    System.out.println("After:  " + Arrays.toString(array) + "\n" + "Counter = " + count);
}

}

【问题讨论】:

  • Arrays.sort(array);
  • 你为什么要关心语句的数量
  • 我不太明白您如何将语句数量视为绩效衡量标准
  • 也许您可以通过codegolf.stackexchange.com 激励某人,尽管他们通常以字节计,而不是语句。但我相信你会在那里的某个地方找到打高尔夫球的排序算法;)
  • 这种情况下最快的方法是声明输出oarray[100],然后将每个值分配到输出中的位置。 v = array[i]; oarray[v-1] = v;

标签: java algorithm sorting


【解决方案1】:

示例中最快的算法是快速排序,正如您所问的,我相信这也需要最少的语句。您可以在下面找到一个链接以及它的工作原理说明。

https://www.geeksforgeeks.org/quick-sort/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-02
    • 2016-07-03
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    相关资源
    最近更新 更多