您的位置:首页 > 其它

快排的递归与非递归

2017-11-10 14:33 127 查看
分治类型的算法,一般都存在递归解法和非递归解法两种,对于应用分治思想的快速排序算法,也给出两种实现。

private static void Partition(int[] a,int low,int high){
if(a===null||low>high||low<0||high<0)
return ;
int i=low;int j=high;int point=a[low];
while(i<j){
while(i<j&&a[j]>=point)
j--;
if(i<j)
a[i++]=a[j];a[j]=point;
while(i<j&&a[i]<=point)
i++;
if(i<j)
a[j--]=a[i];a[i]=point;
}
return i;
}


递归:

public void QuickSort(int[] a,int low,high){
if(a=null||low<0||high<0||low>high)
return ;
int point=partition(a,low,high);
QuickSort(a,low,point-1);
QuickSort(a,point+1,high);
}


非递归:利用栈

public void QuickSort(int[] a,int low,int high){
if(a=null||low<0||high<0||low>high)
return ;
Stack<Integer> s=new Stack<>();
s.push(low);s.push(high);
while(!s.empty()){
int i=s.peek();
int j=s.peek();
if(i<j){
int k=partition(a,i,j);
if(k>i){
s.push(i);
s.push(k-1);
}else{
s.push(k+1);
s.push(j);
}
}
}


在一般情况下,非递归比递归响应时间更快,递归在处理问题时要反复调用函数,这增大了它的空间和时间开销。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息