#### Sorting Algorithm and Dichotomy Search

• Please fill in the code so that mySort () can display the passed parameters in descending order.

``````function mySort() {
var tags = new Array();
for (var i = 0; i < arguments.length; i++) {
tags.push(arguments[i]);
}
tags.sort(function sortNum(a, b) {
return a - b;
});
return tags;
}

var result = mySort(50, 11, 16, 32, 24, 99, 57, 100);
console.info(result);``````
• Bubble sort

``````function bubbleSort(arr) {
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr.length - i; j++) {
var temp = 0;
// ">" 从小到大排序
// "<" 从大到小排序
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}``````
• Quick sort

`````` function quickSort(elements) {
if (elements.length <= 1) {
return elements;
}
var pivotIndex = Math.floor(elements.length / 2);
var pivot = elements.splice(pivotIndex, 1)[0];
var left = [];
var right = [];
for (var i = 0; i < elements.length; i++) {
if (elements[i] < pivot) {
left.push(elements[i]);
} else {
right.push(elements[i]);
}
}
return quickSort(left).concat([pivot], quickSort(right));
}``````
• Insertion sort

``````insertSort = function (elements) {
var i = 1,
j, step, key, len = elements.length;
for (; i < len; i++) {
step = j = i;
key = elements[j];
while (--j > -1) {
if (elements[j] > key) {
elements[j + 1] = elements[j];
} else {
break;
}
}
elements[j + 1] = key;
}
return elements;
};``````
• Binary Search-Recursive Method

``````function binarySearch(arr, key, leftIndex, rightIndex) {
if (leftIndex > rightIndex) {
return -1;
}
var mid = parseInt((leftIndex + rightIndex) / 2);
if (arr[mid] == key) {
return mid;
} else if (arr[mid] > key) {
rightIndex = mid - 1;
return binarySearch(arr, key, leftIndex, rightIndex);
} else if (arr[mid] < key) {
leftIndex = mid + 1;
return binarySearch(arr, key, leftIndex, rightIndex);
}
}``````
• Binary Search-Non-Recursive Method

``````function binarySearch(arr, key) {
var leftIndex = 0,
rightIndex = arr.length - 1;
while (leftIndex <= rightIndex) {
var mid = parseInt((leftIndex + rightIndex) / 2);
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
leftIndex = mid + 1;
} else if (arr[mid] > key) {
rightIndex = mid - 1;
} else {
return -1;
}
}
}``````