var data = Array.from({length: 20}, () => Math.floor(Math.random() * 100));
function swap(array, a, b) {
[array[a], array[b]] = [array[b], array[a]];
}
function boubleSort(array) {
for (let i = 0; i < array.length - 1; i++) {
for (let j = 0; j < array.length - 1 - i; j++) {
if (array[j] > array[j + 1]) {
swap(array, j, j + 1);
}
}
}
return array;
}
function boubleSort(array) {
let hasChange = true;
for (let i = 0; i < array.length - 1 && hasChange; i++) {
hasChange = false;
for (let j = 0; j < array.length - 1 - i; j++) {
if (array[j] > array[j + 1]) {
swap(array, j, j + 1);
hasChange = true;
}
}
}
return array;
}
function selectSort(array) {
for (let i = 0; i < array.length; i++) {
let min = i;
for (let j = i + 1; j < array.length; j++) {
if (array[j] < array[min]) {
min = j
}
}
if (min !== i) {
swap(array, i, min);
}
}
return array;
}
function insertSort(array) {
let i, j;
let current;
for (let i = 1; i < array.length; i++) {
if (array[i] < array[i - 1]) {
current = array[i];
j = i - 1;
for (; j >=0 && array[j] > current; j--) {
array[j + 1] = array[j]
}
array[j + 1] = current;
}
}
return array;
}
function merge(a, b) {
let i = 0;
let j = 0;
const result = [];
while (i < a.length && j < b.length) {
if (a[i] < b[j]) {
result.push(a[i++]);
} else {
result.push(b[j++]);
}
}
while (i < a.length) {
result.push(a[i++]);
}
while (j < b.length) {
result.push(b[j++]);
}
return result;
}
function mergeSort(array) {
if (array.length <= 1) {
return array;
}
const mid = Math.floor(array.length / 2);
const left = array.slice(0, mid);
const right = array.slice(mid);
return merge(mergeSort(left), mergeSort(right));
}
function quickSort(array) {
if (array.length <= 1) {
return array;
}
const pivot = array[0];
const left = [];
const right = [];
for (let i = 1; i < array.length; i++) {
if (array[i] < pivot) {
left.push(array[i]);
} else {
right.push(array[i]);
}
}
return quickSort(left).concat(pivot, quickSort(right));
}
console.log(data);
console.log(boubleSort([...data]));
console.log(selectSort([...data]));
console.log(insertSort([...data]));
console.log(mergeSort([...data]));
console.log(quickSort([...data]));