5大排序算法之javascript实现

发布于2017年8月17日 09:21:36 ,最后一次修改于2018年2月02日 11:16:52

排序算法是基础算法。虽然关键在于算法的思想而不是语言,但还是决定借助算法可视化工具结合自己常用的语言实现一遍。

5大排序如下:

    • 冒泡排序
    • 选择排序
    • 插入排序
    • 合并排序
    • 快速排序

已上5大排序测试结果如下:

  • 下面来具体介绍下:
1、冒泡排序

基本思路:

1.依次比较相邻的两个数,如果第一个比第二个小,不变。如果第一个比第二个大,调换顺序。一轮下来,最后一个是最大的数

2.对除了最后一个之外的数重复第一步,直到只剩一个数

图形展示:

代码实现:

// 冒泡排序
function bubbleSort(myArray) {
varlen=myArray.length;
vari;
varj;
varstop;
for(i=0;i<len-1;i++){
for(j=0,stop=len-1-i;j<stop;j++){
if(myArray[j]>myArray[j+1]){
swap(myArray,j,j+1);
}
}
}
returnmyArray;
}
function swap(myArray, p1, p2) {
vartemp=myArray[p1];
myArray[p1]=myArray[p2];
myArray[p2]=temp;
}
2、选择排序

基本思路:

1.找出最小的数,和第一个交换位置

2.在剩下的数中,找出最二小的数,放在第二个

3.依次类推,排出顺序

图形展示:

代码实现:

// 选择排序
function selectionSort(myArray) {
varlen=myArray.length,
min;
for(i=0;i<len;i++){
// 将当前位置设为最小值
min=i;
// 检查数组其余部分是否更小
for(j=i+1;j<len;j++){
if(myArray[j]<myArray[min]){
min=j;
}
}
// 如果当前位置不是最小值,将其换为最小值
if(i!=min){
swap(myArray,i,min);
}
}
returnmyArray;
}
function swap(myArray, p1, p2) {
vartemp=myArray[p1];
myArray[p1]=myArray[p2];
myArray[p2]=temp;
}
3、插入排序

基本思路:

1.把数组分为[已排序]和[未排序]两部分,第一个数为[已排序],其余为[未排序]

2.从[未排序]抽出第一个数,和[已排序]部分比较,插入到合适的位置

图形展示:

代码实现:

// 插入排序
function insertionSort(myArray) {
varlen=myArray.length,// 数组的长度
value,// 当前比较的值
i,// 未排序部分的当前位置
j;// 已排序部分的当前位置
for(i=0;i<len;i++){
// 储存当前位置的值
value=myArray[i];
/*
* 当已排序部分的当前元素大于value,
* 就将当前元素向后移一位,再将前一位与value比较
*/
for(j=i-1;j>-1&&myArray[j]>value;j--){
myArray[j+1]=myArray[j];
}
myArray[j+1]=value;
}
returnmyArray;
}
4、合并排序(分而治之)

基本思路:

1.不断将数组对半分,直到每个数组只有一个

2.将分出来的部分重新合并

3.合并的时候按顺序排列

图形展示:

代码实现:

// 合并排序
// 被拆分的数组重新合并
function merge(left, right) {
varresult=[],
left_index=0,
right_index=0;
// 将两个数组合并
// 合并的时候按从小到大的顺序
while(left_index<left.length&&right_index<right.length){
if(left[left_index]<right[right_index]){
result.push(left[left_index++]);
}else{
result.push(right[right_index++]);
}
}
// 和其他数组拼接
returnresult.concat(left.slice(left_index)).concat(right.slice(right_index));
}
function mergeSort(myArray) {
// 只有一个数的时候退出递归
if(myArray.length<2){
returnmyArray;
}
varmiddle=Math.floor(myArray.length/2),
left=myArray.slice(0,middle),
right=myArray.slice(middle);
// 递归
// 不断拆分只到一个数组只有一个数
returnmerge(mergeSort(left),mergeSort(right));
}
5、快速排序

基本思路:

1.以一个数为基准(中间的数),比基准小的放到左边,比基准大的放到右边

2.再按此方法对这两部分数据分别进行快速排序(递归进行)

3.不能再分后退出递归,并重新将数组合并

图形展示:

代码实现:

// 快速排序
function quickSort(myArray) {
// 当被分的数组只剩一个时,退出递归
if(myArray.length<=1){
returnmyArray;
}
// 中间基准值的index
varpivotIndex=Math.floor(myArray.length/2);
// 基准值
varpivot=myArray.splice(pivotIndex,1)[0];
varleft=[];
varright=[];
// 小的放左边,大的放右边
for(vari=0;i<myArray.length;i++){
if(myArray[i]<pivot){
left.push(myArray[i]);
}else{
right.push(myArray[i]);
}
}
// 递归
// 把数组合并在一起
returnquickSort(left).concat([pivot],quickSort(right));
};

本文共 28 个回复

  • mind vault 2025/10/14 23:56

    **mind vault** mind vault is a premium cognitive support formula created for adults 45+. It’s thoughtfully designed to help maintain clear thinking

  • sugarmute 2025/10/19 01:38

    **sugarmute** sugarmute is a science-guided nutritional supplement created to help maintain balanced blood sugar while supporting steady energy and mental clarity.

  • glpro 2025/10/19 05:54

    **glpro** glpro is a natural dietary supplement designed to promote balanced blood sugar levels and curb sugar cravings.

  • prostadine 2025/10/19 09:38

    **prostadine** prostadine is a next-generation prostate support formula designed to help maintain, restore, and enhance optimal male prostate performance.

  • vitta burn 2025/10/19 15:16

    **vitta burn** vitta burn is a liquid dietary supplement formulated to support healthy weight reduction by increasing metabolic rate, reducing hunger, and promoting fat loss.

  • glucore 2025/10/19 15:23

    **glucore** glucore is a nutritional supplement that is given to patients daily to assist in maintaining healthy blood sugar and metabolic rates.

  • prodentim 2025/10/19 15:25

    **prodentim** prodentim an advanced probiotic formulation designed to support exceptional oral hygiene while fortifying teeth and gums.

  • synaptigen 2025/10/19 15:43

    **synaptigen** synaptigen is a next-generation brain support supplement that blends natural nootropics, adaptogens

  • nitric boost 2025/10/19 15:44

    **nitric boost** nitric boost is a dietary formula crafted to enhance vitality and promote overall well-being.

  • mitolyn 2025/10/19 18:12

    **mitolyn** mitolyn a nature-inspired supplement crafted to elevate metabolic activity and support sustainable weight management.

  • wildgut 2025/10/19 18:19

    **wildgut** wildgutis a precision-crafted nutritional blend designed to nurture your dog’s digestive tract.

  • zencortex 2025/10/19 18:31

    **zencortex** zencortex contains only the natural ingredients that are effective in supporting incredible hearing naturally.

  • yusleep 2025/10/19 19:22

    **yusleep** yusleep is a gentle, nano-enhanced nightly blend designed to help you drift off quickly, stay asleep longer, and wake feeling clear.

  • breathe 2025/10/20 02:48

    **breathe** breathe is a plant-powered tincture crafted to promote lung performance and enhance your breathing quality.

  • pineal xt 2025/10/20 15:28

    **pineal xt** pinealxt is a revolutionary supplement that promotes proper pineal gland function and energy levels to support healthy body function.

  • energeia 2025/10/20 15:54

    **energeia** energeia is the first and only recipe that targets the root cause of stubborn belly fat and Deadly visceral fat.

  • prostabliss 2025/10/20 16:47

    **prostabliss** prostabliss is a carefully developed dietary formula aimed at nurturing prostate vitality and improving urinary comfort.

  • boostaro 2025/10/20 17:15

    **boostaro** boostaro is a specially crafted dietary supplement for men who want to elevate their overall health and vitality.

  • potent stream 2025/10/20 21:55

    **potent stream** potent stream is engineered to promote prostate well-being by counteracting the residue that can build up from hard-water minerals within the urinary tract.

  • hepato burn 2025/10/21 13:25

    **hepato burn** hepato burn is a premium nutritional formula designed to enhance liver function, boost metabolism, and support natural fat breakdown.

  • hepato burn 2025/10/21 17:58

    **hepato burn** hepato burn is a potent, plant-based formula created to promote optimal liver performance and naturally stimulate fat-burning mechanisms.

  • flowforce max 2025/10/22 03:08

    **flowforce max** flowforce max delivers a forward-thinking, plant-focused way to support prostate health—while also helping maintain everyday energy, libido, and overall vitality.

  • prodentim 2025/10/22 04:29

    **prodentim** prodentim is a forward-thinking oral wellness blend crafted to nurture and maintain a balanced mouth microbiome.

  • cellufend 2025/10/22 04:58

    **cellufend** cellufend is a natural supplement developed to support balanced blood sugar levels through a blend of botanical extracts and essential nutrients.

  • revitag 2025/10/22 06:09

    **revitag** revitag is a daily skin-support formula created to promote a healthy complexion and visibly diminish the appearance of skin tags.

  • neurogenica 2025/10/22 06:13

    **neurogenica** neurogenica is a dietary supplement formulated to support nerve health and ease discomfort associated with neuropathy.

  • sleeplean 2025/10/23 06:19

    **sleeplean** sleeplean is a US-trusted, naturally focused nighttime support formula that helps your body burn fat while you rest.

  • memory lift 2025/10/25 00:46

    **memory lift** memory lift is an innovative dietary formula designed to naturally nurture brain wellness and sharpen cognitive performance.

发表评论