- 二分查詢(折半查詢)
- 遞迴
- 反轉
- 氣泡排序
- 二分查詢(含遞迴)
- 原理:先折半一分為二,開始比較,再折半一分為二.......
- 優點:查詢效率比利用迴圈高
- 要求:必須是一個有序的陣列,例[1,3,5,7]
- 例子:
let arr = [22,21,16,14,10,7,5,3,1];
function dichotomy(min,max,num){
let mid =Math.floor((max+min)/2);
if(arr[mid]==num){
return mid;
};
if(num<arr[mid]){
return dichotomy(mid+1,max,num);
};
if(num>arr[mid]){
return dichotomy(0,mid-1,num);
};
};
let i = dichotomy(0,arr.length-1,14);
console.log(i);
複製程式碼
2.反轉
//原理
let str = 'abcdef';
let arr = str.split('');
let i=0, j = arr.length-1;
while(i<j){
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
};
console.log(arr);
//通過陣列方法
let str = 'abcdef';
let arr = str.split('').reverse().join('');
console.log(arr);
複製程式碼
3.氣泡排序
- 原理:迴圈巢狀,不斷的交換位置
let arr = [21,11,44,21,12,14,32,,53];
for(let i=0;i<arr.length;i++){
for(let j=0;j<arr.length;j++){
if(arr[i]>arr[j]){
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
console.log(arr);
//第一項
[11,21,44,21,12,14,32,53]
//第二項
[21,11,44,21,12,14,32,53]
//第三項
[44,21,11,21,12,14,32,53]
//第四項
[44,21,21,11,12,14,32,53]
//第五項
[44,21,21,12,11,14,32,53]
//第六項
[44,21,21,14,12,11,32,53]
//第七項
[44,31,21,21,14,12,11,53]
//第八項
[53,44,31,21,21,14,12,11]
複製程式碼