基于字符串“weight”排序

时间:2016-09-06 08:29:27

标签: javascript algorithm sorting

我在互联网上搜索了一种排序算法,该算法以“自然”方式对表格的条目进行排序,因此inline-block10之后,依此类推,但我发现没有一种解决方案是“完美契合“。

现在我正在研究自己的解决方案来进行排序算法。我现在的问题是,如果根据abc中字母的位置和特定字符串中该字母的位置为表格行中的每个字符串创建一个数字是否有效且适用,然后按此创建的数字排序? / p>

示例:

1将是abc,然后每个字母的“权重”应该更高,字符串长度为:

a = 1; b = 2; c= 3

所以a = 1 * 1(pos in str); b = 2 * 2; c = 3 * 3将是14作为数字。

我不希望这是一种真正的自然类型。

我使用了库和内置的Javascript函数“.sort()”,但它们不适用于abc92593c17-5183-4db1-b4bd-d538abb4124b这样的字符串,所以对我来说这不对。

这是按字母“重量”对字符串进行排序的好方法吗?

1 个答案:

答案 0 :(得分:1)

使用localeCompate()查看这个小例子:



var s1 = '92593c17-5183-4db1-b4bd-d538abb4124';
var s2 = 'ed06d686-8a04-4ae1-9500-975fb85a49d9';
var s3 = '10';
var s4 = '1';
var s5 = 'a';
var s6 = 4;

$('#1').text(s1 + ' before ' + s2 + ': ' + (s1.toString().localeCompare(s2.toString()) == -1 ? 'yes' : 'no'));
$('#2').text(s2 + ' before ' + s3 + ': ' + (s2.toString().localeCompare(s3.toString()) == -1 ? 'yes' : 'no'));
$('#3').text(s3 + ' before ' + s4 + ': ' + (s3.toString().localeCompare(s4.toString()) == -1 ? 'yes' : 'no'));
$('#4').text(s4 + ' before ' + s5 + ': ' + (s4.toString().localeCompare(s5.toString()) == -1 ? 'yes' : 'no'));
$('#5').text(s5 + ' before ' + s6 + ': ' + (s5.toString().localeCompare(s6.toString()) == -1 ? 'yes' : 'no'));
$('#6').text(s6 + ' before ' + s1 + ': ' + (s6.toString().localeCompare(s1.toString()) == -1 ? 'yes' : 'no'));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='1'></p>
<p id='2'></p>
<p id='3'></p>
<p id='4'></p>
<p id='5'></p>
<p id='6'></p>
&#13;
&#13;
&#13;

相关问题