Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 使用时间复杂度为0(1)的选择算法对排序后的数组进行排序_Algorithm_Sorting_Selection Sort - Fatal编程技术网

Algorithm 使用时间复杂度为0(1)的选择算法对排序后的数组进行排序

Algorithm 使用时间复杂度为0(1)的选择算法对排序后的数组进行排序,algorithm,sorting,selection-sort,Algorithm,Sorting,Selection Sort,如果数组已排序,则如何停止排序。按选择排序的排序数组的时间复杂度为0(1) static void sort(int a[]){ int min; for(int i=0;i<a.length-1;i++){ min=i; for(int j=i+1;j<a.length;j++) { if(a[j]<a[min]) min=j;

如果数组已排序,则如何停止排序。按选择排序的排序数组的时间复杂度为0(1)

static void sort(int a[]){
   int min;
     for(int i=0;i<a.length-1;i++){
         min=i;
         for(int j=i+1;j<a.length;j++)
         {

             if(a[j]<a[min])
                 min=j;

         }
         if(min==0){
             System.out.print("min" + min);
             break;
         }
         int temp=a[min];
         a[min]=a[i];
         a[i]=temp;

     }
    System.out.print(Arrays.toString(a) );

 }
静态无效排序(int a[]{
int-min;
对于(inti=0;i你所拥有的是一个数组,当数组被排序时,它不容易使自己“提前退出”

想想它在做什么:

  • 找到数组中最小的项并将其放置在位置0
  • 找到剩余的最小项目并将其放置在位置1
  • 重复,找到第k个最小的项目并将其放置在位置k,直到k=n
  • 该算法不会进行任何比较以查看数组的其余部分是否有序

    我想你可以加上这样一句话:

    static void sort(int a[]) {
       for(int i=0;i<a.length-1;i++){
           Boolean isSorted = true;
           Boolean didExchange = false;
           int min=i;
           for(int j=i+1;j<a.length;j++)
           {
               if(a[j]<a[min])
               {
                   min=j;
               }
               if (a[j] < a[j-1])
               {
                   // if at any point an item is smaller than its predecessor,
                   // then the array is not sorted.
                   isSorted = false;
               }
           }
           if (min != i)
           {
               didExchange = true;
               int temp=a[min];
               a[min]=a[i];
               a[i]=temp;
           }
           // If no exchange was made, and isSorted is still true,
           // then the array is sorted.
           if (isSorted && !didExchange)
           {
               break;
           }
       }
       System.out.print(Arrays.toString(a) );
    
    静态无效排序(int a[]{
    for(int i=0;i和)具有更好的实际性能,并且两者都更容易修改以检测已排序的数组。事实上,您根本不需要修改插入排序;“早出”只是基本算法的一部分


    顺便说一句,即使数组被排序,这也需要O(n)。您无法确定数组是否按O(1)排序,因为您必须检查所有n项。

    O(1)
    中进行排序是不可能的。这需要
    O(n)
    只是检查数组是否已排序。请尽可能使用适当的英语,因为您的要求并不完全清楚。