我正在学习如何创建排序算法,并且正在制作快速排序算法。我按照教程进行操作,但更改了代码,但它没有显示预期的结果。我拥有的数组是
[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);
这是解决方案。 https://repl.it/@IT18117110/237WRFDQW
你犯了很多错误。我已经评论过你在哪里拥有它们