数据结构Self-Organizing Lists的三种启发式算法:count,move-to-front,transpose的C++实现
demo变量设置
char ori[8] = { 'A','B','C','D','E','F','G','H' };
int count[8] = { 0,0,0,0, 0,0,0,0 };
char in[12] = { 'F','D','F','G','E','G','F','A','D','F','G','E' };
int ans = 0;
count
/* 这是count算法,访问某元素后,如果前面的访问次数比它小,那么它会一直往前交换 */
for (int i = 0; i < 12; i++) {
int index = 0;
for (int j = 0; j < 8; j++) {
if (ori[j] == in[i]) {
index = j;
count[j]++;
break;
}
}
ans += (index+1);
while (index > 0 && count[index]>count[index-1]) {
swap(ori, index, index - 1);
swap(count, index, index - 1);
index--;
}
}
move-to-front
/* 这是 move-to-front算法 访问就移到最前 只是不会被淘汰 */
for (int i = 0; i < 12; i++) {
int index = 0;
for (int j = 0; j < 8; j++) {
if (ori[j] == in[i]) {
index = j;
break;
}
}
ans += (index+1);
while (index > 0) {
swap(ori, index, index - 1);
index--;
}
}
transpose
/* 这是 transpose算法 访问次数增加的元素,只会和前一个比较 */
for (int i = 0; i < 12; i++) {
int index = 0;
for (int j = 0; j < 8; j++) {
if (ori[j] == in[i]) {
index = j;
break;
}
}
ans += (index+1);
if (index != 0)
swap(ori, index, index - 1);
}
简单输出比较次数和最终结果
cout << ans << endl;
cout << ori << endl;