This article mainly shares with you the detailed explanation of Js bubble sort and quick sort. I hope it can help you.
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]
Related recommendations:
A simple js bubble sort example
JS bubble sort selection sort and insertion sort example analysis
Detailed explanation of php bubble, selection, insertion and quick sort algorithm
The above is the detailed content of Detailed explanation of JS bubble sort and quick sort. For more information, please follow other related articles on the PHP Chinese website!