冒泡排序和快速排序

冒泡排序和快速排序

冒泡排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function paixu(arr) {
var temp;

for (let i = 0; i < arr.length; i++) {

for (let j = 0; j < i+1; j++) {

if (arr[j] > arr[j+1]) {
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
}

}
}

return arr
}
var arr = [1, 4, 2, 2, 3, 5, 6, 9, 34, 23, 12]

console.log(arr);
console.log(paixu(arr));

快速排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function fastxu(arr) {
if (arr.length <= 1) {
return arr
}
var middelIndex = Math.floor(arr.length/2)
var middle = arr[middelIndex]
arr.splice(middelIndex, 1)

var left = []
var right = []
for (let i = 0; i < arr.length; i++) {
if (arr[i] > middle) {
left.push(arr[i])
} else {
right.push(arr[i])
}
}
return fastxu(left).concat([middle], fastxu(right))
}
var arr = [1, 4, 2, 2, 3, 5, 6, 9, 34, 23, 12]

console.log(arr);
console.log(fastxu(arr));