並べ替えアルゴリズムと二分割検索


  • は、コードを充填して、mySort()が入ってきたパラメータを小さい時から大きい順に表示させてください.
  • 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);
  • 発泡体並べ替え
  • function bubbleSort(arr) {
        for (var i = 0; i < arr.length; i++) {
            for (var j = 0; j < arr.length - i; j++) {
                var temp = 0;
                // ">"       
                // " arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        return arr;
    }
  • 快速並べ替え
  •  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));
    }
  • 並べ替えを挿入する
  • 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;
    };
  • 分検索-再帰方法
  • 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);
        }
    }
  • 分検索-非再帰的方法
  • 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;
            }
        }
    }