Skip to content

Commit 163f10e

Browse files
committed
finished chapter 8
bucket sort - non-linked-list version
1 parent 595609a commit 163f10e

File tree

4 files changed

+72
-1
lines changed

4 files changed

+72
-1
lines changed

Utils.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,18 @@ util.randomArrayWithNegatives = (to) => {
2727
return A
2828
}
2929

30+
util.randomArrayBetween0And1 = (n) => {
31+
A = []
32+
for (let i = 0; i < n; i++) {
33+
let num = Math.random()
34+
while(num == 1){
35+
num = Math.random()
36+
}
37+
A.push(num)
38+
}
39+
return A
40+
}
41+
3042
util.AlgorithmInfoLog = (algorithm, A, print_array = true, print_time = true, print_memory = true) => {
3143
print_array && console.log(chalk.blue([A[0]]))
3244
print_time && console.time(algorithm.name)

ch_2/insertion_sort.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ insertion_sort = (A) => {
33
key = A[j]
44
// insert A[j] into the sorted sub sequence A[0,...,j-1]
55
i = j - 1
6-
while(i >= 0 && A[i] < key){
6+
while(i >= 0 && A[i] > key){
77
// copy each element to its right position
88
A[i + 1] = A[i]
99
i -= 1

ch_8/Problems/Problems_8_2_b.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
const utils = require('../../Utils')
2+
3+
// 0(n)
4+
const sort = (A) => {
5+
let i = -1
6+
let j = A.length
7+
while (i < j) {
8+
while (A[i] != 1 && i < j) {
9+
i++
10+
}
11+
while (A[j] != 0 && j > i) {
12+
j--
13+
}
14+
utils.exchange(A, i, j)
15+
i++
16+
j--
17+
}
18+
}
19+
20+
21+
let A = [0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1]
22+
sort(A)
23+
console.log(A)

ch_8/bucket_sort.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* This is the non-linked-list version
3+
* I'm just using arrays as buckets,
4+
* Actually this is very slow now, because of the
5+
* Array.prototype.concat function,
6+
* I'll be implementing the linked-list version
7+
* in future chapters
8+
*/
9+
const Utils = require('../Utils')
10+
const insertion_sort = require('../ch_2/insertion_sort')
11+
12+
bucket_sort = (A) => {
13+
let B = []
14+
let C = []
15+
let n = A.length
16+
for (i in A) {
17+
B.push(new Array())
18+
}
19+
20+
for (let i = 0; i < n; i++) {
21+
B[Math.floor(n * A[i])].push(A[i])
22+
}
23+
24+
for (let i = 0; i < n; i++) {
25+
insertion_sort(B[i])
26+
}
27+
28+
for (let i = 0; i < n; i++) {
29+
C = C.concat(B[i])
30+
}
31+
32+
return C
33+
}
34+
35+
let A = Utils.randomArrayBetween0And1(10000)
36+
Utils.AlgorithmInfoLog(bucket_sort, [A], false)

0 commit comments

Comments
 (0)