冒泡排序、选择排序、插入排序
1.冒泡排序(两层循环,两两互换)
function bubbleSort ( data ) { var temp = 0; for ( var i = data.length ; i > 0 ; i -- ){ for( var j = 0 ; j < i - 1 ; j++){ if( data[j] > data[j + 1] ){ temp = data[j]; data[j] = data [j+1]; data[j+1] = temp; } } } return data; }
2.选择排序
function selectionSort( data ) { for( var i = 0; i< data.length ; i++){ var min = data[i]; var temp; var index = i; for( var j = i + 1; j< data.length; j++){ if( data[j] < min ){ min = data[j]; index = j; } } temp = data[i]; data[i] = min; data[index]= temp; } return data; }
3.插入排序
function insertionSort( data ) { var len = data.length; for (var i = 1; i < len; i++) { var key = data[i]; var j = i - 1; while ( j >= 0 && data[j] > key) { data[j + 1] = data[j]; j--; } data[j + 1] = key; } return data; }