为什么我的Java快速排序没有移植到Javascript中?
我已经用Java实现了快速排序,但是当我将它移植到JS时,它没有正确排序。什么给 测试用例:{5,86,69,73,11,17,5,86,1,74,34,31000,1} 分类后 爪哇:1117374861000 JS:1 3 1 34 86 74 1000 5 11 69 17 73 86 Java代码为什么我的Java快速排序没有移植到Javascript中?,javascript,java,algorithm,sorting,Javascript,Java,Algorithm,Sorting,我已经用Java实现了快速排序,但是当我将它移植到JS时,它没有正确排序。什么给 测试用例:{5,86,69,73,11,17,5,86,1,74,34,31000,1} 分类后 爪哇:1117374861000 JS:1 3 1 34 86 74 1000 5 11 69 17 73 86 Java代码 public class QuickSort { /** * @param args the command line arguments */ public static void m
public class QuickSort {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);
int[] arr = new int[]{5,86,69,73,11,17,5,86,1,74,34,3, 1000, 1};
quickSort(arr, 0, arr.length - 1);
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
private static void quickSort(int[] arr, int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
// calculate pivot number, I am taking pivot as middle index number
int pivot = arr[lowerIndex+(higherIndex-lowerIndex)/2];
// Divide into two arrays
while (i <= j) {
/**
* In each iteration, we will identify a number from left side which
* is greater then the pivot value, and also we will identify a number
* from right side which is less then the pivot value. Once the search
* is done, then we exchange both numbers.
*/
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
if (i <= j) {
swap(arr, i, j);
//move index to next position on both sides
i++;
j--;
}
}
// call quickSort() method recursively
if (lowerIndex < j)
quickSort(arr, lowerIndex, j);
if (i < higherIndex)
quickSort(arr, i, higherIndex);
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
公共类快速排序{
/**
*@param指定命令行参数
*/
公共静态void main(字符串[]args){
//int[]newArray=Arrays.copyOfRange(oldArray、startIndex、endIndex);
int[]arr=新的int[]{5,86,69,73,11,17,5,86,1,74,34,3,1000,1};
快速排序(arr,0,arr.length-1);
对于(int i=0;i 如果(iJS varriable)没有清晰的类型,请小心,您的问题如下:
var pivot = arr[parseInt(lowerIndex + (higherIndex - lowerIndex)/2)];
JS varriable没有清晰的类型,因此请小心,您的问题如下:
var pivot = arr[parseInt(lowerIndex + (higherIndex - lowerIndex)/2)];
我已经更新了您的小提琴,它现在应该可以为您工作。您的端口的问题是这条线路:
var pivot = arr[lowerIndex + (higherIndex - lowerIndex)/2];
这是因为在javascript中,除以2可能会导致小数点为0.5。为了解决此问题,请使用Math.floor()
确保正确舍入该值。例如:
var pivot = arr[Math.floor(lowerIndex + (higherIndex - lowerIndex) / 2)];
我已经更新了您的小提琴,它现在应该可以为您工作。您的端口的问题是这条线路:
var pivot = arr[lowerIndex + (higherIndex - lowerIndex)/2];
这是因为在javascript中,除以2可能会导致小数点为0.5。为了解决此问题,请使用Math.floor()
确保正确舍入该值。例如:
var pivot = arr[Math.floor(lowerIndex + (higherIndex - lowerIndex) / 2)];
谢谢!我习惯于Java取整整数,所以下次我会更小心:)谢谢!我习惯于Java取整整数,所以下次我会更小心:)