zoukankan      html  css  js  c++  java
  • Algs4-2.3.5只有两种主键值的数组排序

    1)从数组两端向中间找到第一对不同的值,然后将大值作为分界值。
    2)从数组两端向中间找,左端找到等于大值时停止找,右端找到小于大值时停止找。
    3)交换上面找到的两个值。
    4)如此反复第2、第3步,直到中间相遇时结束。
    注意:如果数据只有一种值时,代码不能正确运行。
    public class E2d3d5
    {
        public static void sort(Comparable[] a)
        {
           if (a.length<2) return;
           Comparable max=findMax(a);
           int lo=0;
           int hi=a.length-1;
            while(true)
              {
                while(less(a[lo],max)) lo++;
                while(!less(a[hi],max))hi--;
                if(lo>=hi) break;
                exch(a,lo,hi); 
              }
        }
     
        private static Comparable findMax(Comparable[] a)
        {
            Comparable max=a[0];
            int lo=1;
            int hi=a.length-1;
            while(lo<=hi)
            {
                if (less(max,a[lo])  || less(a[lo],max))
                {
                    if(less(max,a[lo])) max=a[lo];
                    break;
                }
               
                if (less(max,a[hi])  || less(a[hi],max))
                {
                    if(less(max,a[hi])) max=a[hi];
                    break;
                }
                lo++;
                hi--;
            }//end while
            return max;
        }//end findMax

       
        private static boolean less(Comparable v,Comparable w)
        { return v.compareTo(w)<0;}
       
        private static void exch(Comparable[] a,int i,int j)
        {
            Comparable  t=a[i];
            a[i]=a[j];
            a[j]=t;
        }
       
        private static void show(Comparable[] a)
        {
            for (int i=0;i<a.length;i++)
                StdOut.print(a[i]+" ");
            StdOut.println();
        }
       
        public static boolean isSorted(Comparable[] a)
        {
            for (int i=1;i<a.length;i++)
                if(less(a[i],a[i-1])) return false;
            return true;
        }
       
        public static void main(String[] args)
        {
            String[] a=In.readStrings();
            sort(a);
            assert  isSorted(a);
            show(a);
        }
    }

  • 相关阅读:
    【leetcode】1215.Stepping Numbers
    【leetcode】1214.Two Sum BSTs
    【leetcode】1213.Intersection of Three Sorted Arrays
    【leetcode】1210. Minimum Moves to Reach Target with Rotations
    【leetcode】1209. Remove All Adjacent Duplicates in String II
    【leetcode】1208. Get Equal Substrings Within Budget
    【leetcode】1207. Unique Number of Occurrences
    【leetcode】689. Maximum Sum of 3 Non-Overlapping Subarrays
    【leetcode】LCP 3. Programmable Robot
    【leetcode】LCP 1. Guess Numbers
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9860190.html
Copyright © 2011-2022 走看看