冒泡排序
//原理:每次都是前后两两比较然后根据大小交换位置(可以从小到大,或者相反)//1.prepare swap fnfunction swap(array,index1,index2) { var aux = array[index1]; array[index1] = array[index2]; array[index2] = aux;}//2.double forfunction bubbleSort(arr){ let length = arr.length for (let i=0;i<length;i++){ for (let j=0;j<length-1;j++){ if (arr[j] > arr[j+1]){ swap(arr,j,j+1) } } console.log(arr) //过程 } console.log('result',arr) //结果}let test = [1,5,4,3,2]bubbleSort(test)
控制台运行实例: