繁体   English   中英

对可比较值的数组进行排序

[英]Sorting Arrays of Comparable Values

我正在开发一个使用基于键的索引的组件,该索引对一组引用对象(高级字典)中的项目进行排序。

当键由一个项目组成时,比较机制的排序很好,但是当我为此增加一个维度的复杂性时,我就失去了排序的精度。

var key1 = new Key{Values=new[]{23,56}};
var key2 = new Key{Values=new[]{23,58}};

// i will be -1 because the first component of key1 is equal to 
// the first component of key2
var i = key1.Compare(key2);

为了获得键的排序因子,我使用了键的单个组成部分比较的代数加法。 我感觉我做的不对,因为当组件的值之间的差异较大时,不遵守顺序

var key1 = new Key{Values=new[]{23,92}};
var key2 = new Key{Values=new[]{33,45}};

// i will be 0 because the first component of key1 is less than 
// the first component of key2, but the second component of 
// key1 is more than the second component of key2, while I'd
// expect a -1
// -1 + 1 = 0
var i = key1.Compare(key2);

排序发生错误是因为键的整个组成部分被认为具有同等重要性,而我想按位置对比较因子进行排名

有没有人遇到过同样的情况? 我有什么想念的吗?

注意 :请考虑在我的示例中比较的值是数字,但实际上对象类型是变量,但是所有IComparable

比较第一个组件:如果结果不为零,则将其返回。 否则,比较第二个分量,返回结果。

这称为词典顺序。

您基本上可以遍历所有字段,并在比较器函数中一一比较。

// Assuming A and B have same length 
bool comparator( const A[],  const B[]){
   for(i = 0 ; i < A.length; i++)
   if ( A[i] <= B[i])
   continue;
   else
   return true;

  return false;

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM