Common algorithms for Javascript implementation (e.g. Bubble fast pigeon nest parity etc.)

• 2020-03-30 02:44:18
• OfStack

``````
l = [6, 2, 4, 1, 98, 34, 5, 9, 23, 8, 10, 32]

//Bubble sort

//Quick sort
/*function quickSort(arr) {
if (arr.length <= 1) return arr;
var left = [],
right = [],
middle = [];
var mid = arr[Math.floor(arr.length / 2)]
for (var i = 0; i < arr.length; i++) {
if (arr[i] < mid) {
left.push(arr[i]);
} else if (arr[i] > mid) {
right.push(arr[i]);
} else {
middle.push(mid);
}
}
return [].concat(quickSort(left), middle, quickSort(right))

}

var results = quickSort(l)
console.log(results)

*/

//Selection sort

//Insertion sort

//Bucket sort

//Pigeon nest sort, non-negative integer

//Merge sort
/*function mergeSort(arr) {
if (arr.length <= 1) return arr;
var mid = Math.floor(arr.length / 2);
var left = MergeSort(arr.slice(0, mid));
var right = MergeSort(arr.slice(mid));
var result = [];

while (left.length && right.length) {
if (left[left.length - 1] <= right[0]) {
result = result.concat(left);
left = [];
} else if (right[right.length - 1] < left[0]) {
result = result.concat(right);
right = [];
} else {
if (right[0] < left[0]) {
result.push(right.shift());
} else {
result.push(left.shift());
}
}
}
result = result.concat(left, right);

return result;
}*/

/*function mergeSort(arr) {
var merge = function(left, right) {
var result = [];
while (left.length > 0 && right.length > 0) {
if (left[0] < right[0]) {
result.push(left.shift());
} else {
result.push(right.shift());
}
}
return result.concat(left).concat(right);
}

if (arr.length == 1) return arr;
var middle = Math.floor(arr.length / 2),
left = arr.slice(0, middle),
right = arr.slice(middle);
return merge(mergeSort(left), mergeSort(right));
}

var results = mergeSort(l)
console.log(results)

*/

//Heap sort

//Parity is arranged

function oddEvenSort(arr) {
var swaped = true;
while (swaped) {
swaped = false;
for (var i = 0; i < arr.length; i += 2) {
if (arr[i] > arr[i + 1]) {
arr[i] = [arr[i + 1], arr[i + 1] = arr[i]][0];
swaped = true;
}
}
for (var i = 1; i < arr.length; i += 2) {
if (arr[i] > arr[i + 1]) {
arr[i] = [arr[i + 1], arr[i + 1] = arr[i]][0];
swaped = true;
}
}
}
return arr;
}

var results = oddEvenSort(l)
console.log(results)
``````

Related articles: