Applications of Classical Sorting Algorithms

1. Sort an almost ordered array

  Problem: Given an array arr, the number of elements is N, and the order of moving the elements after sorting it does not exceed K, where K<<N.

  analyze:

     1. The time complexity of sorting such as bubble sort, selection sort, quick sort, and merge sort has nothing to do with the state of the array.

     2. Insertion sort complexity is O(N*K)

     3. The improved heap sort can do O(N*logK)

  Improved heap sort:

  1. Considering that each move does not exceed K, the smallest element is in 0..K.

  2. Build a small heap from 0...K to get the smallest element arr[0].

  3. Pop up the top of the heap, put the next element that is not in the heap into the top of the heap, and filter down.

  4. Repeat 3 until no new elements can be added, the last element of the heap is placed on the top of the heap, the last element of the heap is deleted, the filter is down, and the top of the heap is popped.

  5. The heap is empty and the array is sorted.

 vector<int> percDown(vector<int> A,int p,int r){
        int parent,child;
        int key=A[p];
        for(parent=p;parent*2+1<=r;parent=child){
            child=parent*2+1;
            if(child+1<=r&&A[child]>A[child+1])
                child++;
            if(key<=A[child]) break;
            else{
                A[parent]=A[child];
            }
        }
        A[parent]=key;
        return A;
    }


    vector<int> sortElement(vector<int> A, int n, int k) {
        // write code here
        //建立小堆
        for(int j=(k-1)/2;j>=0;j--)
            A=percDown(A,j,k);

        vector<int> res;
        int heaplast=k;
        for(int i=0;i<n;i++){
            res.push_back(A[0]);
            int last=i+k+1;

            if(last>n-1) {
                A[0]=A[heaplast--];
                A=percDown(A,0,heaplast);
            }else{
                A[0]=A[last];
                A=percDown(A,0,k);
            }
        }
        return res;
    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325330968&siteId=291194637
Recommended