-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselection_sort.js
58 lines (53 loc) · 1.26 KB
/
selection_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
let arreglo = [9, 8, 4, 3, 2, 1, 3, 6, 8, 5, 4, 7, 6, 5, 4, 2, 3, 1]
function selection_sort(list)
{
let sorted = 0;
let min_sorted_index = 0;
while(!sorted)
{
let index_less_so_far = min_sorted_index;
for(let i = min_sorted_index; i < list.length; i++)
{
if(list[i + 1] < list[index_less_so_far])
{
index_less_so_far = i + 1;
}
}
if(min_sorted_index != index_less_so_far)
{
let swap_helper = list[min_sorted_index];
list[min_sorted_index] = list[index_less_so_far];
list[index_less_so_far] = swap_helper;
}
if((list.length - 1) - (min_sorted_index - 1) == 1)
{
if(list[min_sorted_index - 1] < list[list.length - 1])
sorted = true;
}
min_sorted_index++;
}
return list;
}
console.log(selection_sort(arreglo));
function selection_sort_book(list)
{
for(let i = 0; i < list.length - 1; i++)
{
let lowestNumberIndex = i;
for(let j = i + 1; j < list.length; j++)
{
if(list[j] < list[lowestNumberIndex])
{
lowestNumberIndex = j;
}
}
if(lowestNumberIndex != i)
{
let temp = list[i];
list[i] = list[lowestNumberIndex];
list[lowestNumberIndex] = temp;
}
}
return list;
}
console.log(selection_sort_book(arreglo));