java中quicksort的参数,在Java中实现QuickSort的一些问题

Here is my code:

public class Main

{

public static void main(String[] args)

{

int[] temp = {4,2,6,4,5,2,9,7,11,0,-1,4,-5};

quickSort(temp);

for(int s : temp) System.out.println(s);

}

public static void quickSort(int[] data)

{

quickSort(data, 0, data.length);

}

public static void quickSort(int[] data, int first, int n)

{

int p, n1, n2;

if(n > 1)

{

p = partition(data, first, n);

n1 = p - first;

n2 = n - n1 - 1;

quickSort(data, first, n1);

quickSort(data, p+1, n2);

}

}

private static int partition(int[] A, int first, int n )

{

int right = first + n - 1;

int ls = first;

int pivot = A[first];

for(int i = first+1; i <= right; i++)

{

if(A[i] <= pivot)

// Move items smaller than pivot only, to location that would be at left of pivot

{

ls++;

swap(A[i], A[ls]);

}

}

swap(A[first], A[ls]);

return ls;

}

private static void swap(int i, int j)

{

int temp = i;

i = j;

j = temp;

}

}

After running this program, it does not sort the array and prints the same array without sorting.

4

2

6

4

5

2

9

7

11

0

-1

4

-5

What is the wrong in this implementation?

解决方案

The problem is that your swap() function doesn't actually swap elements in an array, it just swaps the values in two integer variables. Integers are passed in Java by value, not by reference.

Replace this with a swap function that re-assigns the array values such as:

private static void swap(int[] array, int pos1, int pos2) {

int temp = array[pos1];

array[pos1] = array[pos2];

array[pos2] = temp;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值