前言
本次來分享一下排序的api底層的邏輯,這次用js模擬,java的邏輯也是差不多。
先看封裝好的api例子:
js的sort排序
java的compareTo排序
自己模擬的代碼(JS)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
function compareTo(a,b){ return a-b; //a-b為從下到大 b-a為從大到小 } Object.prototype.newSort = function (Func){ const flag = Func(1,0); const $ this = this ; // 注意:上面for循環(huán)的$this.length-1是因為這里只需要走到倒數(shù)第二個位置即可,而下面的for循環(huán)$this.length-1是數(shù)組下標對應的最后一個值 for (let i = 0; i < $ this .length-1; i++){ for (let j = $ this .length-1; j > i; j--){ // 思路就是從數(shù)組第一個開始與倒數(shù)第一個向上直到數(shù)組第二個的過程中一直比較,如果有比第一個小的,就交換,然后第二次循環(huán)就只需要第二個與倒數(shù)第二個開始比較,以此類推 const compare = flag > 0 ? $ this [i] > $ this [j] : $ this [i] < $ this [j]; if (compare){ //滿足條件就進行位運算來交換位置 $ this [i] = $ this [i] ^ $ this [j]; $ this [j] = $ this [i] ^ $ this [j]; $ this [i] = $ this [i] ^ $ this [j]; } } } } var array = [2,1,5,7,3,4,9,8,6,4,5,2,1]; console.log(array.newSort(compareTo)); //[ 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 7, 8, 9 ] |
源代碼
js源代碼
java源代碼
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/zxd66666/p/13194458.html