Algorithmic questions - fast sorting

Posted by void_function on Sat, 04 Apr 2020 06:30:37 +0200

Given a set of intervals, please merge all overlapping intervals.

Example:
//Give [1,3],[2,6],[8,10],[15,18],
//Return [1,6],[8,10],[15,18].

//Known:
    static class Interval {
        int start;
        int end;
        Interval() { start = 0; end = 0; }
        Interval(int s, int e) { start = s; end = e; }
        @Override
        public String toString() {
            // TODO Auto-generated method stub
            return start+"";
        }
    }

//Ask:
    public static ArrayList<Interval> quicksort(ArrayList<Interval> list){
        // Start your show
    }

Use the java encapsulated sort () method to answer:

public static List<Interval> merge(List<Interval> intervals) {
        if(intervals.size()<2){
            return intervals;
        }
        List<Interval> mList=new ArrayList();
        intervals.sort(new Comparator<Interval>() {

            @Override
            public int compare(Interval arg0, Interval arg1) {
                // TODO Auto-generated method stub
                System.out.println("arg0="+arg0.start+",arg1="+arg1.start);
                return arg0.start-arg1.start;
            }

        });
        Interval l1=intervals.get(0);
        mList.add(l1);
        for(int i=1; i<intervals.size(); i++){
            Interval l2=intervals.get(i);
            if(l1.end>=l2.start){
                l1.end=Math.max(l1.end, l2.end);
                mList.set(mList.size()-1, l1);
            }else{
                mList.add(l2);
                l1=l2;
            }
        }
        return mList;

    }

Continue to see:
In fact, this is a fast sorting algorithm. If we don't use the sort method, we can write it ourselves.

    public static ArrayList<Interval> quicksort(ArrayList<Interval> list){
        if(list.size()<2){
            return list;
        }
        Interval pivot=list.get(0);
        ArrayList<Interval> mList=new ArrayList<>();
        ArrayList<Interval> less=new ArrayList<>();
        ArrayList<Interval> greater=new ArrayList<>();
        for(int i=1; i<list.size(); i++){
            if(list.get(i).start>pivot.start){
                greater.add(list.get(i));
            }else {
                less.add(list.get(i));
            }

        }
        mList.addAll(quicksort(less));
        mList.add(pivot);
        mList.addAll(quicksort(greater));
        return mList;
    }

Fast sorting uses recursion internally. It only needs to perform three steps:

  1. Select base value
  2. Divide the array into leading sub arrays, and put the array less than the reference value to the left of the reference value, and the array greater than the reference value to the right of the reference value
  3. Repeat the previous two steps to quickly sort the two self data

In the average case, the running time of fast sorting is O(nlog(n)); in the worst case, the running time of this algorithm is O(n^2)

Topics: less Java