Js冒泡排序与快速排序实详解
程序员文章站
2022-03-30 14:54:15
...
本文主要和大家分享Js冒泡排序与快速排序实详解,希望能帮助到大家。
var array = [7, 8, 6, 12, 87, 35, 1, 48, 56, 12, 48, 69, 12, 12, 12, 103, 15, 6, 88, 24, 26, 25, 9, 6];
//冒泡排序 function bubbleSort(arr){ var len = arr.length; for(var i=0; i<len; i++){ var len_j = len - i - 1; for(var j=0; j<len_j; j++){ if(arr[j] > arr[j+1]){ arr[j] = arr[j] ^ arr[j+1]; arr[j+1] = arr[j] ^ arr[j+1]; arr[j] = arr[j] ^ arr[j+1]; } } } } bubbleSort(array); console.log(array); //[1, 6, 6, 6, 7, 8, 9, 12, 12, 12, 12, 12, 15, 24, 25, 26, 35, 48, 48, 56, 69, 87, 88, 103]
//快速排序 function quickSort(arr, low, high){ var staticHigh = high, //获取最初始高位指针 val = arr[low], //把低位当做关键字 index = low; //关键字下标 if(low >= high){ return; } while(low < high){ //如果与关键字相同的,按比关键字大来排序 while(val <= arr[high]){ if(index != high){ //为避免匹配到本身时,错误的把高位下标减1,跳过循环 high--; }else{ break; } } //关键字与高位换位置 arr[index] = arr[high]; arr[high] = val; index = high; while(arr[low] < val){ low++; } //关键字与低位换位置 arr[index] = arr[low]; arr[low] = val; index = low; } quickSort(arr, 0, index-1); //递归前半段 quickSort(arr, index+1, staticHigh); //递归后半段 } quickSort(array, 0, array.length-1); console.log(array); //[1, 6, 6, 6, 7, 8, 9, 12, 12, 12, 12, 12, 15, 24, 25, 26, 35, 48, 48, 56, 69, 87, 88, 103]
相关推荐:
以上就是Js冒泡排序与快速排序实详解的详细内容,更多请关注其它相关文章!