Discuss / JavaScript / 使用insertBefore进行排序

使用insertBefore进行排序

Topic source

Armyja

#1 Created at ... [Delete] [Delete and Lock User]
var
    b,c,i,j,
    list = document.getElementById('test-list');
    for (i = 0; i < list.children.length - 1; i++) {
        c = list.children[i]; 
        for (j = i + 1; j < list.children.length; j++){
            b = list.children[j]; 
            if ( b.innerText < c.innerText )
                list.insertBefore(b, c);
        }
    }

Armyja

#2 Created at ... [Delete] [Delete and Lock User]

一楼有bug,正确代码如下:

var
    b,c,i,j,
    list = document.getElementById('test-list');
    for (i = 0; i < list.children.length - 1; i++) {
        c = list.children[i]; 
        for (j = i + 1; j < list.children.length; j++){
            b = list.children[j]; 
            if ( b.innerText < c.innerText ){
                list.insertBefore(b, c);
                c = list.children[i]; //补充此行
            }
        }
    }

  • 1

Reply