JSデータ構造とアルゴリズム(三)
8924 ワード
JSデータ構造とアルゴリズム(三)
いくつかの並べ替えアルゴリズムは未完です.
いくつかの並べ替えアルゴリズムは未完です.
function Sort() {
swap = function (arr, a, b) {
var tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
};
this.bubbleSort = function (arr) {
var len,
i,
j;
for (i = 0, len = arr.length; i < len; i++) {
for (j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
}
}
return arr;
};
this.selectSort = function (arr) {
var len,
indexMin,
i,
j,
minValue;
for (i = 0, len = arr.length; i < len; i++) {
indexMin = i;
for (j = i; j < len; j++) {
if (arr[j] < arr[indexMin]) {
indexMin = j;
}
}
if (indexMin !== i) {
swap(arr, i, indexMin);
}
}
return arr;
};
this.insertSort = function (arr) {
var i,
j,
len,
tmp;
flag = false;
for (i = 1, len = arr.length; i < len; i++) {
j = i;
tmp = arr[i];
while (j > 0 && arr[j - 1] > tmp) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = tmp;
}
return arr;
};
var merge = function (leftArr, rightArr) {
var res = [],
i = 0,
j = 0,
lenLeft = leftArr.length,
lenRight = rightArr.length;
while (i < lenLeft && j < lenRight) {
if (leftArr[i] < rightArr[j]) {
res.push(leftArr[i++]);
} else {
res.push(rightArr[j++]);
}
}
while (i < lenLeft) {
res.push(leftArr[i++]);
}
while (j < lenRight) {
res.push(rightArr[j++]);
}
return res;
};
var mergeSortRec = function(arr) {
var len = arr.length,
mid,
l,
r;
if (len === 1) {
return arr;
} else {
mid = len >> 1;
l = arr.slice(0, mid);
r = arr.slice(mid, len);
return merge(mergeSortRec(l), mergeSortRec(r));
}
};
this.mergeSort = function (arr) {
arr = mergeSortRec(arr);
return arr;
};
var partition = function (arr, lef, rig) {
var pi = arr[(lef + rig) >> 1],
i = lef,
j = rig;
while (i <= j) {
while (arr[i] < pi) {
i++;
}
while (arr[j] > pi) {
j--;
}
if (i <= j) {
swap(arr, i, j);
i++;
j--;
}
}
return i;
};
var quick = function (arr, lef, rig) {
var index,
len = arr.length;
if (len > 1) {
index = partition(arr, lef, rig);
if (lef < index - 1) {
quick(arr, lef, index - 1);
}
if (rig > index) {
quick(arr, index, rig);
}
}
return arr;
};
this.quickSort = function (arr) {
arr = quick(arr, 0, arr.length - 1);
return arr;
};
this.shellSort = function (arr) {
var len = arr.length,
i,
j,
gap;
for (gap = len >> 1; gap > 0; gap >>= 1) {
for (i = gap; i < len; i++) {
for (j = i - 1; j >= 0 && arr[j] > arr[j + gap]; j -= gap) {
swap(arr, j, j + gap);
}
}
}
return arr;
};
}
var arr = [-1, 7, -5, 9, 3, 4, 6, 8, 4];
var mySort = new Sort();
// arr = mySort.bubbleSort(arr);
// arr = mySort.selectSort(arr);
// arr = mySort.insertSort(arr);
// arr = mySort.mergeSort(arr);
// arr = mySort.quickSort(arr);
// arr = mySort.shellSort(arr);
console.log(arr);