forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlashSort.js
More file actions
Latest commit
87 lines (75 loc) · 1.51 KB
/
Copy pathFlashSort.js
File metadata and controls
87 lines (75 loc) · 1.51 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* Flashsort is a distribution sorting algorithm showing linear
* computational complexity O(n) for uniformly distributed
* data sets and relatively little additional memory requirement.
*
* Wikipedia: https://en.wikipedia.org/wiki/Flashsort
*/
exportfunctionflashSort(arr){
letmax=0
letmin=arr[0]
constn=arr.length
constm=~~(0.45*n)
constl=newArray(m)
for(leti=1;i<n;++i){
if(arr[i]<min){
min=arr[i]
}
if(arr[i]>arr[max]){
max=i
}
}
if(min===arr[max]){
returnarr
}
constc1=(m-1)/(arr[max]-min)
for(letk=0;k<m;k++){
l[k]=0
}
for(letj=0;j<n;++j){
constk=~~(c1*(arr[j]-min))
++l[k]
}
for(letp=1;p<m;++p){
l[p]=l[p]+l[p-1]
}
lethold=arr[max]
arr[max]=arr[0]
arr[0]=hold
// permutation
letmove=0
lett
letflash
letj=0
letk=m-1
while(move<n-1){
while(j>l[k]-1){
++j
k=~~(c1*(arr[j]-min))
}
if(k<0)break
flash=arr[j]
while(j!==l[k]){
k=~~(c1*(flash-min))
hold=arr[(t=--l[k])]
arr[t]=flash
flash=hold
++move
}
}
// insertion
for(j=1;j<n;j++){
hold=arr[j]
leti=j-1
while(i>=0&&arr[i]>hold){
arr[i+1]=arr[i--]
}
arr[i+1]=hold
}
returnarr
}
/**
* Implementation of Flash Sort
*/
// const array = [3, 0, 2, 5, -1, 4, 1, -2]
// flashSort(array)