【问题标题】:QuickSort Java code giving error Time Limit ExceededQuickSort Java 代码给出错误 Time Limit Exceeded
【发布时间】:2020-05-21 12:17:48
【问题描述】:

我正在使用下面的代码使用快速排序算法对给定的数组进行排序。我是一个初学者,正在努力理解为什么我的代码在少数测试用例上运行良好,但在少数测试用例上却失败了。我收到错误超过时间限制。该代码不断未能通过测试用例:- array{5,5,6,8,4,5,6} 。随时提供有关如何更好地编码的提示。

        public static void quickSort(int[] input) {
            quickSort(input, 0 , input.length-1) ;   
        }
        public static void quickSort(int input[] , int startIndex , int endIndex) {
            if(startIndex >= endIndex){
                 return;
            } else{
            int pivot = partition(input, startIndex , endIndex);
            quickSort(input,startIndex , pivot-1) ; 
            quickSort(input , pivot+1 , endIndex) ;
            }
        }

        public static int partition(int input[] ,int startIndex , int endIndex) {
            int pivot = input[startIndex] ; 
            int count  = 0; 
            for(int i = 1+startIndex ; i < input.length ; i++){
                if(input[i] < pivot){
                    count++;
                }
            }
            input[startIndex] = input[startIndex+count]; 
            input[startIndex+count] = pivot ;

            int s = startIndex ; 
            int e = endIndex ;
            int sc = startIndex+count;

            while(s < sc &&  sc < e){
                if(input[s] < pivot) {
                    s++;
                } else if(input[e] >= pivot){
                    e--;
                }else if(input[s] > pivot && input[e] < pivot){
                    int temp = input[e];
                    input[e] = input[s] ; 
                    input[s] = temp;
                    e--;
                    s++;
                    }
            }     
        return sc;
        }    
    }

【问题讨论】:

  • 代码修改了 Hoare 分区方案,以便将枢轴放置在适当的位置。这不是必需的。相反,不要从使用 quickSort(... pivot) 和 quicksort(... pivot+1 ...) 的 2 个递归调用中排除枢轴。看看wiki example,它将条件(if 语句)的数量减少到每个内部循环只有 1 个。

标签: java algorithm sorting data-structures quicksort


【解决方案1】:

乍一看,您似乎在使用索引作为指示子数组限制的一种方式

        public static int partition(int input[] ,int startIndex , int endIndex)

但是你总是迭代整个数组(条件是i &lt; input.length):

for(int i = 1+startIndex ; i < input.length ; i++){
   if(input[i] < pivot){
     count++;
   }
 ...

因此,在您随后的迭代中,您仍在遍历整个数组:

所以在这次通话中:

quickSort(input,startIndex , pivot-1);

pivot -1 在您通过input.length 时被忽略,无论如何都会导致防护条件:

if (startIndex &gt;= endIndex )

永远不会评估为真,因此永远运行。

尝试将你的 for 循环更改为(我自己没有尝试过,只是通过查看代码):

for(int i = 1+startIndex ; i < endIndex ; i++){

然后看看这是否有效。

我希望这会有所帮助。

【讨论】:

  • 再观察一下,如果我们在分区中只有两个元素时避免递归调用(如果需要,使用一个“if”和一个“swap”),这也将节省一些时间。跨度>
猜你喜欢
  • 2022-11-07
  • 2016-09-25
  • 2021-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多