当前位置: 首页 > 面试题库 >

使用Java中的随机数据点快速排序

谢奇略
2023-03-14
问题内容

我被分配去实现一个带有随机枢轴点的快速排序(因为这被认为是最有效/最安全的方法),但是我一直在忙于Bogosort。谁能指导我该怎么做?有人可以帮我看看我的bogosort,看看我是否还能保存它吗?

public static void Quick(int[] target, int lo, int hi) {
    if(hi-lo==0){return;}
    Random numberGenerator = new Random();
    int pivot = (numberGenerator.nextInt(hi-lo)+lo);
    int high;
    for(high=hi; high>pivot ; high--){
        if(target[high]<target[pivot]){ //if highest was smaller than pivot, move far end 
            if(high-pivot==1){
                int temp=target[high];
                target[high]=target[pivot];
                target[pivot]=temp;
            }
            else{
                int temp1 = target[pivot];
                int temp2 = target[pivot+1];
                target[pivot]=target[high];
                target[pivot+1]=temp1;
                target[high]=temp2;
            }
        }
    }
    int low;
    for(low=lo; low<pivot ; low++){
        if(target[low]>target[pivot]){ //if highest was smaller than pivot, move far end
            if(pivot-low==1){
                int temp=target[low];
                target[low]=target[pivot];
                target[pivot]=temp;
            }
            else{
                int temp1 = target[pivot];
                int temp2 = target[pivot-1];
                target[pivot]=target[low];
                target[pivot-1]=temp1;
                target[low]=temp2;
            }
        }
    }
    if(low-lo>0){
        Quick(target, lo, low-1);
    }
    if(hi-high>0){
        Quick(target, high+1, hi);
    }
}

问题答案:

请参阅以下伪代码以进行就地修补(来自Wikipedia):

  function partition(array, left, right, pivotIndex)
     pivotValue := array[pivotIndex]
     swap array[pivotIndex] and array[right] // Move pivot to end
     storeIndex := left
     for i  from  left to right - 1 // left ≤ i < right  
         if array[i] ≤ pivotValue 
             swap array[i] and array[storeIndex]
             storeIndex := storeIndex + 1
     swap array[storeIndex] and array[right] // Move pivot to its final place
     return storeIndex

注意,它遍历整个数组(最后一个索引除外)。直到最后,透视图才被交换。在您的代码中,关键值在整个循环中不断变化,这似乎是不正确的。

每次进行交换时,交换目标(上面的storeIndex)都应更改。

同样,您只需要交换小于左侧枢轴的值。如果所有低值都在左侧,则高值将最终在右侧。



 类似资料:
  • 我对python是全新的,我正在尝试在其中实现quicksort。有人能帮我完成我的代码吗? 我不知道如何连接这三个数组并打印它们。

  • 快速排序(Quicksort)是对冒泡排序的一种改进,是一种排序执行效率很高的排序算法。 快速排序的基本思想是:通过一趟排序,将要排序的数据分隔成独立的两部分,其中一部分的所有数据比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此使整个数据变成有序序列。 具体做法是:假设要对某个数组进行排序,首先需要任意选取一个数据(通常选用第一个数据)作为

  • java中是否有内置的数据结构可以为排序列表提供高效的性能?我还需要修改排序列表,包括插入和删除操作。我首先使用arraylist。我认为在插入和删除的情况下,arraylist的性能可能不够好。什么样的数据结构适合使用?如果没有足够快的内置数据结构,在设计自定义数据结构之前,我可以朝哪个方向走?

  • 我正在尝试使用递归编写快速排序代码,但我得到一个堆栈溢出错误。第二个递归函数给出了连续误差。我只是想不通。

  • 问题内容: 我有一个大于1000万行的巨大表。我需要从中有效地获取5000个随机样本。我有一些限制因素,使我想要的总行数减少到9密耳。 我尝试通过NEWID()使用order,但是该查询将花费很长时间,因为它必须对所有行进行表扫描。 有没有更快的方法可以做到这一点? 问题答案: 如果您可以使用伪随机抽样并且您使用的是SQL Server 2005/2008,则请看一下TABLESAMPLE。例如,