-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbubble_sort.js
58 lines (52 loc) · 1.48 KB
/
bubble_sort.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
function bubble_sort(list)
{
let unsorted_until_inex = list.length - 1;
let last_swap = 0;
let sorted = false;
let steps = 0;
while (!sorted)
{
sorted = true;
for(let i = 0; i < unsorted_until_inex; i++)
{
steps++;
if(list[i] > list[i + 1])
{
let swap = list[i];
list[i] = list[i + 1];
list[i + 1] = swap;
sorted = false;
last_swap = i + 1;
}
}
unsorted_until_inex = last_swap;
}
console.log(`My bubble sort: ${steps}`);
return list;
}
function bubble_sort_in(list)
{
let unsorted_until_inex = list.length - 1;
let sorted = false;
let steps = 0;
while (!sorted)
{
sorted = true;
for(let i = 0; i < unsorted_until_inex; i++)
{
steps++;
if(list[i] > list[i + 1])
{
let swap = list[i];
list[i] = list[i + 1];
list[i + 1] = swap;
sorted = false;
}
}
unsorted_until_inex--;
}
console.log(`Book's bubble sort: ${steps}`);
return list;
}
bubble_sort_in([3, 2, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9])
bubble_sort([3, 2, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9])