Quick Sort - not working properly can you please find where i am missing the logic
class test
{
static int arr[]={1,6,3,4,5,8,11};
static int s=0,temp=0,e=0;
publi开发者_如何学Cc static void main(String [] args)throws Exception
{
QS(arr,0,arr.length-1);
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
}
public static void QS(int arr[] ,int i,int j)throws Exception
{
int key=i;
int low=i+1;
int up=j;
int temp=0;
System.out.println(key);
while(low<=up)
{
do{
low++;
}while(arr[low]<arr[key]);
do{
up--;
}while(arr[up]>arr[key]);
if(low<=up)
{
temp=arr[up];
arr[up]=arr[low];
arr[low]=temp;
}
}
System.out.println(low+"++++"+up);
temp=arr[up];
arr[up]=arr[key];
arr[key]=temp;
if(0<up-1)
QS(arr,i,up-1);
if(low< arr.length-2)
QS(arr,low,j);
}
}
Since this looks like homework, here is my advice:
After the partitioning step, print out your array together with the value and the position of the pivot, and verify visually that the partitioning has been done correctly. If it hasn't been (as I suspect is the case), add some more print statements -- or use a debugger -- to understand where your program is going wrong.
Once the partitioning is working, move on to the recursion. This is comparatively easy: all you have to do is make sure that QS
is calling itself with the correct i
and j
(both times), and that the base case is handled correctly.
I think the issue is with getting the pivot. You can write a separate method for partitioning and probably try to print the same and check if its printing the correct pivot. You can refer the below link about quick sort, it provides organized code snippet also. http://www.algolist.net/Algorithms/Sorting/Quicksort
精彩评论