【问题标题】:Array Not Being Sorted In Quicksort TypeScript数组未在 Quicksort TypeScript 中排序
【发布时间】:2020-04-29 13:10:03
【问题描述】:

我正在学习如何创建排序算法,并且正在制作快速排序算法。我遵循了一个教程,但更改了代码,它没有显示预期的结果。我拥有的数组是[95, 2, 19, 60, 49]。排序后的数组应该为 [2, 19, 49, 60, 95]。

预期结果:[2, 19, 49, 60, 95] 实际结果:[ 95, 2, undefined, 60, 49, <91 empty items>, undefined ]

这是我的 TypeScript 代码:

quicksortEx.ts

// An example of quicksort algorithm
// Packed with a custom array
// And some functions.

// Array
let exArr: number[] = [95, 2, 19, 60, 49]; // Sorted should look like
// 2 19 49 60 95

//The partition (partate) function
function partate(arr: number[], low: number, high: number){
    let pivot: number = arr[high];
    let i: number = (low - 1);

    for (let j = 0; j <= high-1; j++){
        if (arr[j] <= pivot){
            // Code taken from stack overflow
            let temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp; // This litterally swaps the
            // array
            i++; // Add to i
            [arr[i], arr[j] = arr[j], arr[i]] // I dont know
            // ^ Comment out if this doesnt work
        }
    }
    let temp = arr[high];
    arr[i+1] = arr[high];
    arr[high] = temp;
    console.log(arr[i]);
    console.log(arr)
    console.log(arr);
}

function quicksort(arr: number[], low:number, high: number){
    // If low number is smaller than high number
    if (low < high){
        let pi: any = partate(arr, low, high);

        quicksort(arr, low, pi -1);
        quicksort(arr, pi +1, high);
    }  
}

// Lets try it out
quicksort(exArr, 2, 96);

任何帮助将不胜感激...!

【问题讨论】:

    标签: arrays typescript sorting return quicksort


    【解决方案1】:

    这里是解决方案。 https://repl.it/@IT18117110/237WRFDQW

    你犯了很多错误。我已经评论了你在哪里拥有它们

    请尽量避免提出此类问题。努力尝试以非常具体的方式提出问题,而不仅仅是发布代码。 您可以在此处发布之前研究并修复许多错误。

    请在提问前遵循这些提示。 https://stackoverflow.com/help/how-to-ask

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-26
      • 2012-11-02
      • 1970-01-01
      • 2016-01-11
      • 2021-10-04
      • 2020-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多