Является ли это Quick Sort Logi c правильным? - PullRequest
0 голосов
/ 20 февраля 2020

Я пытался внедрить быструю сортировку в Javascript без каких-либо ссылок на код psuedo. Это правильная реализация? если нет, как я могу улучшить его.

const quickSort = (arr = []) => {
  const length = arr.length;
  if (length === 0 || length === 1) {
    return arr;
  }

  const pivot = arr[0];
  const leftArray = [];
  const rightArray = [];
  for (let i = 1; i < length; i++) {
    if (arr[i] < pivot) {
      leftArray.push(arr[i]);
    } else {
      rightArray.push(arr[i]);
    }
  }
  return [...quickSort(leftArray), pivot, ...quickSort(rightArray)];
};

console.log(quickSort([2, 45, 6, 7, 8, 1]));

Я добавил код контрольного примера и выполнил его более 250000 раз.

// Function to generate random array.
const generateRandomArray = n =>
  Array.from({
    length: n
  }, () => Math.floor(Math.random() * n));

// Function to check whether array is sorted.
const checkSorted = (arr = []) => {
  let sorted = true;
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < arr[i - 1]) {
      sorted = false;
      break;
    }
  }
  return sorted;
};

// Testing Quick-Sort
const testQuickSort = () => {
  for (let i = 1; true; i++) {
    const sortedArray = quickSort(generateRandomArray(Date.now() % 100000));
    const isSorted = checkSorted(sortedArray);
    if (!isSorted) {
      console.log("error");
      break;
    }
    console.log("pass", i);
  }
};

testQuickSort();

1 Ответ

0 голосов
/ 20 февраля 2020

Вы можете попробовать следующее решение

function pivot(arr, start = 0, end = arr.length - 1) {
  const swap = (arr, idx1, idx2) => {
    [arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];
  };

  // We are assuming the pivot is always the first element
  let pivot = arr[start];
  let swapIdx = start;

  for (let i = start + 1; i <= end; i++) {
    if (pivot > arr[i]) {
      swapIdx++;
      swap(arr, swapIdx, i);
    }
  }

  // Swap the pivot from the start the swapPoint
  swap(arr, start, swapIdx);
  return swapIdx;
}


function quickSort(arr, left = 0, right = arr.length -1){
    if(left < right){
        let pivotIndex = pivot(arr, left, right) //3
        //left
        quickSort(arr,left,pivotIndex-1);
        //right
        quickSort(arr,pivotIndex+1,right);
      }
     return arr;
} 
           
console.log(quickSort([100,-3,2,4,6,9,1,2,5,3,23]));
...