public static void sort(int[] a){
if (a.length>1){
int pivot=a[a.length-1];
int left=0;
int right=a.length-1;
while(left<=right){
while(a[left]<pivot)
left++;
while(a[right]>pivot)
right--;
if(left<=right){
int tmp=a[right];
a[right]=a[left];
a[left]=tmp;
left++;
right--;
}
}
int[] tmp1=new int[right];
for(int i=0;i<tmp1.length;i++)
tmp1[i]=a[i];
int[] tmp2=new int[a.length-right-1];
for(int i=left;i<a.length;i++)
tmp2[i-left]=a[i];
sort(tmp1);
sort(tmp2);
}
}
Im trying to write a quicksort algorithm with one function and it doesn't work. Any help is aprrecitated. Thanks
EDIT: I solved it thanks everyone for your input.
I think the problem is that at the end you are not using the tmp1
and tmp2
to conform the new array a
... Here is a way to do it without creating others arrays:
public static void sort(int[] a, int left, int right){
if (left < right){
int pivot = a[right];
int pos = left - 1;
for (int i = left; i < right; i++)
if (a[i] <= pivot)
Swap(a, ++pos, i);
Swap(a, pos + 1, right);
sort(a, left, pos);
sort(a, pos + 1, right);
}
}
public static void Swap(int[] a, int i, int j){
int temp = a[j];
a[j] = a[i];
a[i] = temp;
}
The first call of sort must be sort(a, 0, a.length - 1)
I hope this helps you
Your sort method seems extremely compared to most int sort methods. Here is a quick and easy one.
public static void sort(int[] intArray){
int n = intArray.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(intArray[j-1] > intArray[j]){
temp = intArray[j-1];
intArray[j-1] = intArray[j];
intArray[j] = temp;
}
}
}
}
This is just a bubble sort. I don't see the point of the recursion. There a bunch of other types of sorts but for a short array length this is the easiest (IMO). Look up some other ones, its kinda cool what they do ( Sorting algorithm ).
To get to your question.... Like @RobinCurbelo said, you didn't use temp1
and temp2
correctly. Your idea is there but I think you were thinking too much into what you needed to do.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.