[英]Quick sort Error java
public int partition(int[]a,int i,int j){
int x=a[i];
int c=i;
for (int d = c+1; d < j; d++) {
if (a[d]<=x) {
c=c+1;
exchange(a, c, d);
}
}
exchange(a, c, i);
return c;
}
public void exchange(int[]a,int c,int d){
int temp=a[c];
a[c]=a[d];
a[d]=temp;
}
public void sort(int[]a,int i,int j){
int index;
if(i<j){
index=partition(a, i, j);
sort(a, i, index-1);
sort(a,index+1, j);
}
}
**strong text**public static void main(String[] args) {
// TODO code application logic here
QUICKSORT abir=new QUICKSORT();
abir.PRINT(abir.a);
abir.sort(abir.a, 0,10);
abir.PRINT(abir.a);
}
Here is my QuickSort code. 这是我的QuickSort代码。 If i enter [6 10 13 5 8 3 2 11] it prints [2 5 3 6 8 11 10 13] 如果我输入[6 10 13 5 8 3 2 11],则会打印[2 5 3 6 8 11 10 13]
Can anyone explain whats wrong with my code??? 谁能解释我的代码有什么问题吗??? THank you 谢谢
Your code seems quite strange to me, where did you take that? 您的代码对我来说似乎很奇怪,您从哪儿拿来的? Anyway why don't you take a look at this page for an explanation of quick sort? 无论如何,为什么不浏览此页面以获取快速排序的说明? http://www.algolist.net/Algorithms/Sorting/Quicksort http://www.algolist.net/Algorithms/Sorting/Quicksort
int partition(int arr[], int left, int right)
{
int i = left, j = right;
int tmp;
int pivot = arr[(left + right) / 2];
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
};
return i;
}
void sort(int arr[], int left, int right) {
int index = partition(arr, left, right);
if (left < index - 1)
sort(arr, left, index - 1);
if (index < right)
sort(arr, index, right);
}
static int[] a = {6, 10, 13, 5, 8, 3, 2, 11};
public static void main(String[] args) {
// TODO code application logic here
QUICKSORT abir=new QUICKSORT();
System.out.println(Arrays.toString(a));
abir.sort(a, 0, 7);
System.out.println(Arrays.toString(a));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.