您的位置:首页 > 职场人生

新浪面试题 快速排序非递归实现

2015-09-21 16:03 274 查看
int Partition(int *a,int low,int high)

{

while(low<high)

{

while(low<high && a[high] >= a[low])

--high;

swap(a[low],a[high]);

while(low<high && a[low] <= a[high])

++low;

swap(a[low],a[high]);

}

return low;

}

void quickSort(int *a,int low ,int high) {

if(a== NULL || low< 0 || high <0)

return ;

stack<int> s;

if(low<high)

{

int pivot = Partition(a,low,high);

if(low < pivot -1)

{

s.push(low);

s.push(pivot-1);

}

if(pivot+1 < high)

{

s.push(pivot+1);

s.push(high);

}

while(!s.empty())

{

int start = s.top();

s.pop();

int end = s.top();

s.pop();

pivot = Partition(a,start,end);

if(start < pivot -1 )

{

s.push(start);

s.push(pivot-1);

}

if(pivot+1 < end)

{

s.push(pivot+1);

s.push(end);

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: