c_cpp 对几乎排序(或K排序)的数组进行排序,插入排序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 对几乎排序(或K排序)的数组进行排序,插入排序相关的知识,希望对你有一定的参考价值。

/*
Given an array of n elements, where each element is at most k away from its target 
position, devise an algorithm that sorts in O(n log k) time. 
For example, let us consider k is 2, an element at index 7 in the sorted array, 
can be at indexes 5, 6, 7, 8, 9 in the given array.
*/

// solution 1, insertion sort, O(N*k)
void insertion_sort(int A[], int N) {
    for(int i=1; i<N; i++) {
        int j = i;
        int key = A[i];
        while(j > 0 && A[j-1] > key) {
            A[j] = A[j-1];
            j--;
        }
        A[j] = key;
    }
}

// solution 2, use min heap, O(Nlogk)
/*  http://www.geeksforgeeks.org/nearly-sorted-algorithm/
We can sort such arrays more efficiently with the help of Heap data structure. Following is the detailed process that uses Heap.
1) Create a Min Heap of size k+1 with first k+1 elements. This will take O(k) time (See this GFact)
2) One by one remove min element from heap, put it in result array, and add a new element to heap from remaining elements.

Removing an element and adding a new element to min heap will take Logk time. So overall complexity will be O(k) + O((n-k)*logK)
*/

以上是关于c_cpp 对几乎排序(或K排序)的数组进行排序,插入排序的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 找到大量数字中最大的k数。您无法对数组进行排序。

c_cpp 给出一个大小为N的数组,其内容为0,1或2(当然重复)。一次性对数组进行排序。

c_cpp 搜索几乎排序的数组

c_cpp 根据给定值的绝对差值对数组进行排序

c_cpp 按设置位的降序对数组进行排序

小范围排序