📌  相关文章
📜  使用函子根据具有给定值的绝对差对数组进行排序

📅  最后修改于: 2021-04-26 10:11:22             🧑  作者: Mango

给定n个不同元素的数组和x个数,请根据与x的绝对差来排列数组元素,即,具有最小差的元素排在最前面,依此类推。
注意:如果两个或多个元素之间的距离相等,请按照与给定数组中相同的顺序排列它们。

例子:

方法:
上述问题已在以下文章中进行了解释:
根据给定值的绝对差对数组进行排序
根据给定值的绝对差对数组进行排序(“使用恒定的额外空间”)

上述解决方案的时间复杂度分别为O(nlogn)和O(n ^ 2),其中O(n)的辅助空间为O(n),O(n ^ 2)的辅助空间为O(1)。在这篇文章中,提出了一种使用O(1)辅助空间的O(nlogn)时间复杂度的解决方案。

该解决方案基于Functors。将给定数字k的差的绝对值与数组值arr [i]进行比较,如果第一个对象的值小于第二个对象的值,则返回true。使用stable_sort等效值的顺序被保留。

下面是上述方法的实现:

// C++ program to sort an array according
// absolute difference with x.
#include 
using namespace std;
  
// Functor class to perform comparison
class compare {
private:
    int num;
  
public:
    compare(int n)
    {
        num = n;
    }
  
    // Overloads () operator to perform
    // the desired comparison
    int operator()(int arr_num1, int arr_num2)
    {
        return abs(num - arr_num1) <
                          abs(num - arr_num2);
    }
};
  
// Function to sort an array according to
// absolute difference with x.
void rearrange(int arr[], int n, int k)
{
    // stable_sort sorts all the values in
    // non-decreasing order and preserves the
    // order of elements with equal values
    stable_sort(arr, arr + n, compare(k));
}
  
// Function to print the array
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
}
  
// Driver code
int main()
{
    int arr[] = { 10, 5, 3, 9, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 7;
  
    rearrange(arr, n, k);
  
    printArray(arr, n);
  
    return 0;
}
输出:
5 9 10 3 2

时间复杂度: O(n Log n)
辅助空间: O(1)