# 算法学习笔记：排序算法(一)

william

## 冒泡排序

``````function bubbleSort(arr) {
for (var i = 0; i < arr.length - 1; i++) {
for (var j = 0; j < arr.length - i - 1; j++) {
var temp;
if (arr[j] > arr[j + 1]) { // 相邻两个元素比较，大的往后移动
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
}
}
}
console.log(arr)
}
bubbleSort([3,44,38,5,47,15,36,26,27,2,46,4,19,50,48])``````

## 选择排序

``````function selectionSort(arr) {
var index,temp // index:最小值下标索引，temp:临时变量
for (var i = 0; i < arr.length; i++) {
index = i
for (var j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[index]) {
index = j
}
}
temp = arr[i]
arr[i] = arr[index]
arr[index] = temp
}
console.log(arr)
}
selectionSort([3,44,38,5,47,15,36,26,27,2,46,4,19,50,48])``````

## 插入排序

``````function insetSort(arr) {
for (var i = 0; i < arr.length; i++) {
var temp = arr[i] // 提取出来的元素
var j = i - 1
while (arr[j] > temp) { // 比较已排序元素和当前提取出来的元素
arr[j+1] = arr[j]
j--
}
arr[j+1] = temp
}
console.log(arr)
}
insetSort([3,44,38,5,47,15,36,26,27,2,46,4,19,50,48])``````

love and share

2.6k 声望
824 粉丝
0 条评论