Detailed explanation of JS bubble sort and quick sort

小云云
Release: 2018-03-10 15:20:44
Original
1996 people have browsed it

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];
Copy after login
//冒泡排序 function bubbleSort(arr){ var len = arr.length; for(var i=0; i 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]
Copy after login
//快速排序 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]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!