题目:在一个数组中,每一个数左边比当前数小的数累加起来,叫做这个数组的小和。求一个数组的小和。
javascript
function randomArr(size, value) {
var length = Math.floor((size + 1) * Math.random())
var arr = []
for(var i = 0; i < length; i++) {
arr[i] = Math.floor((value + 1) * Math.random())
}
return arr
}
function sort(arr) {
if(arr.length < 1) {
return 0
}
return mergeSort(arr, 0, arr.length - 1)
}
function mergeSort(arr, l, r) {
if(l === r) {
return 0
}
var min = Math.floor((r + l) / 2)
return mergeSort(arr, l, min) + mergeSort(arr, min + 1, r) + merge(arr, l, r, min)
}
function merge(arr, l, r, min) {
var p1 = l
var p2 = min + 1
var a = []
var i = 0
var sum = 0
while(p1 <= min && p2 <= r) {
if(arr[p1] - arr[p2] < 0) {
sum += arr[p1] * (r - p2 + 1)
a[i] = arr[p1]
i++
p1++
} else {
a[i] = arr[p2]
i++
p2++
}
}
while(p1 <= min) {
a[i] = arr[p1]
i++
p1++
}
while(p2 <= r) {
a[i] = arr[p2]
i++
p2++
}
arr.splice(l, r - l + 1, ...a)
return sum
}
function rightWay(arr) {
if(arr.length < 1) {
return 0
}
var sum = 0
for(var i = 0; i < arr.length; i++) {
for(var j = 0; j < i; j++) {
if(arr[j] < arr[i]) {
sum += arr[j]
}
}
}
return sum
}
function logarithm() {
var time = 50000
var size = 10
var value = 100
for(var i = 0; i < time; i++) {
var arr1 = randomArr(size, value)
var arr2 = [...arr1]
var arr3 = [...arr1]
var sum2 = rightWay(arr2)
var sum3 = sort(arr3)
if(sum2 !== sum3) {
console.log('arr1', arr1)
console.log('arr2', arr2)
console.log('arr3', arr3)
break;
}
}
if(i >= time) {
console.log('你写的算法是对的')
}
}
logarithm()