js快速排序算法

真正的快速排序算法一:

function quickSort(array){
	function sort(prev, numsize){
		var nonius = prev;
		var j = numsize -1;
		var flag = array[prev];
		if ((numsize - prev) > 1) {
			while(nonius < j){
				for(; nonius < j; j--){
					if (array[j] < flag) {
						array[nonius++] = array[j]; //a[i] = a[j]; i += 1;
						break;
					};
				}
				for( ; nonius < j; nonius++){
					if (array[nonius] > flag){
						array[j--] = array[nonius];
						break;
					}
				}
			}
			array[nonius] = flag;
			sort(0, nonius);
			sort(nonius + 1, numsize);
		}
	}
	sort(0, array.length);
	return array;
}
console.log(quickSort([23,11,89,45,67,76,56,99]))
快速排序算法二:

function swap(items, firstIndex, secondIndex){
    var temp = items[firstIndex];
    items[firstIndex] = items[secondIndex];
    items[secondIndex] = temp;
}

function partition(items, left, right) {

    var pivot   = items[Math.floor((right + left) / 2)],
        i       = left,
        j       = right;


    while (i <= j) {

        while (items[i] < pivot) {
            i++;
        }

        while (items[j] > pivot) {
            j--;
        }

        if (i <= j) {
            swap(items, i, j);
            i++;
            j--;
        }
    }

    return i;
}

function quickSort(items, left, right) {

    var index;

    if (items.length > 1) {

        left = typeof left != "number" ? 0 : left;
        right = typeof right != "number" ? items.length - 1 : right;

        index = partition(items, left, right);

        if (left < index - 1) {
            quickSort(items, left, index - 1);
        }

        if (index < right) {
            quickSort(items, index, right);
        }

    }

    return items;
}

var items = [4, 2, 6, 5, 3, 9];
// first call
var result = quickSort(items);
var result2 = quickSort(items, 0, items.length - 1);

 

快速排序算法三:

"快速排序"的思想很簡單,整個排序過程只須要三步:
      (1)在數據集之中,選擇一個元素做爲"基準"(pivot)。

  (2)全部小於"基準"的元素,都移到"基準"的左邊;全部大於"基準"的元素,都移到"基準"的右邊。

  (3)對"基準"左邊和右邊的兩個子集,不斷重複第一步和第二步,直到全部子集只剩下一個元素爲止。

var quickSort = function(arr) {

  if (arr.length <= 1) { return arr; }

  var pivotIndex = Math.floor(arr.length / 2);

  var pivot = arr.splice(pivotIndex, 1)[0];

  var left = [];

  var right = [];

  for (var i = 0; i < arr.length; i++){

    if (arr[i] < pivot) {

      left.push(arr[i]);

    } else {

      right.push(arr[i]);

    }

  }

  return quickSort(left).concat([pivot], quickSort(right));

};
console.log(quickSort([23,11,89,45,67,76,56,99]))
相關文章
相關標籤/搜索