您的位置:首页 > 其它

快排非递归实现

2015-08-07 00:42 375 查看
int partition(int* arr, int low, int high)

{

int pivot = arr[low];

while(low < high)

{

while(low < high && arr[high] >= pivot)

high--;

arr[low] = arr[high];

while(low < high && arr[low] <= pivot)

low--;

arr[high] = arr[low];

}

arr[low] = pivot;

return low;

}

void non_recursive_qsort(int* arr, int low, int high)

{

stack<int> s;

int pivot;

if(low < high)

return ;

pivot = partition(arr, low, high)

if(low < pivot - 1)

{

s.push(low);

s.push(pivot - 1);

}

if(high > pivot + 1)

{

s.push(high);

s.push(pivot + 1);

}

//其实就是用栈保存每一个待排序子串的首尾元素下标,下一次while循环时取出这个范围,对这段子序列进行partition操作

//如果pivot的左段或右段已经少于两个元素了,则无需再对这个子段partition了

while(!s.empty())

{

high = s.top();

s.pop();

low = s.top();

s.pop();

pivot = partition(arr, low, high)

if(low < pivot - 1)

{

s.push(low);

s.push(pivot - 1);

}

if(high > pivot + 1)

{

s.push(high);

s.push(pivot + 1);

}

}

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