【问题标题】:Based on what is a sorting algorithm considered efficient?基于什么被认为是有效的排序算法?
【发布时间】:2015-05-27 00:27:54
【问题描述】:

我已经实现了一种排序算法来对无序整数数组进行排序。如果我放入一个 100,000 元素的数组,则返回大约需要 10,500 百万秒。我的算法是快还是非常慢?下面是代码。

public static void sort(int[] array) {
    int lastItem = array[array.length - 1];
    int length = array.length;
    for (int j = 0; j < array.length; j++) {

        for (int i = 0; i < length; i++) {

            if (array[i] > lastItem) {
                array[length-1] = array[i];
                array[i] = lastItem;
                lastItem = array[length - 1];
            }
        }
        length--;
        if (length > 1) lastItem = array[length - 1];
    }
}

【问题讨论】:

  • 如果您在谈论“实施性能”:将其与同一阵列的Arrays#sort 进行比较。看看哪个更快。如果您在谈论“算法复杂性”:您的似乎有二次运行时间。阵列大 10 倍,速度慢 100 倍。不太好。
  • 如果你使用 java8 请阅读stackoverflow.com/questions/23170832/… 这个链接有很多很好的例子winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples
  • 您应该计算算法的 Big-O 时间,然后将其与其他已知算法进行比较。这是最好的方法。单个数据点告诉您的信息很少。
  • 还是 O(n^2) 不太好。
  • 非常感谢。因为我是编程和东西的新手。所以我还不是很了解。但是从你们的回答来看。我想我现在该去哪里了。

标签: java algorithm sorting


【解决方案1】:

您的算法使用的是冒泡排序,它需要 o(n^2)。对于较大的输入,它可能会很慢。为什么不使用可以在 O(nlogn) 中达到您想要的结果的快速排序?

这是一些代码,请注意最好选择枢轴作为中间元素。

/**
 * o(nlogn) - high probability otherwise o(n SQUARE)
 * 
 * 
 * Choose a pivot value. We take the value of the middle element 
 * as pivot value, but it can be any value, which is in range of 
 * sorted values, even if it doesn't present in the array.
 * 
 * Partition. Rearrange elements in such a way, that all elements 
 * which are lesser than the pivot go to the left part of the array 
 * and all elements greater than the pivot, go to the right part 
 * of the array. Values equal to the pivot can stay in any part 
 * of the array. Notice, that array may be divided in non-equal parts.
 * 
 * Sort both parts. Apply quicksort algorithm recursively to the left 
 * and the right parts.
 * 
 * @param input
 */
public void quickSort(int[] input, int start, int end){
    if( start < end ){
        int pindex = findParition(input, start, end);
        quickSort(input, start, pindex-1);
        quickSort(input, pindex+1, end);
    }
}

/**
 * findParition for quick sort
 * @param input
 * @param start
 * @param end
 * @return
 */
private int findParition(int[] input, int start, int end) {
    int pivot = input[end];
    int pindex = start;

    for( int i = start; i < end; i++){
        if( input[i] <= pivot ){
            int temp = input[pindex];
            input[pindex] = input[i];
            input[i] = temp;

            pindex++;
        }
    }

    int temp = input[pindex];
    input[pindex] = input[end];
    input[end] = temp;

    return pindex;
}

【讨论】:

    【解决方案2】:

    Click here 比较各种类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 2011-08-22
      • 2020-12-30
      • 2010-11-26
      相关资源
      最近更新 更多