quickSort 的递归与迭代实现

本文详细介绍了快速排序算法的递归和迭代两种实现方式。通过讲解和示例代码,阐述了如何使用自定义栈进行迭代实现,以及如何进行元素拆分和排序。代码已拆分为多个辅助函数,方便理解和学习。
摘要由CSDN通过智能技术生成

递归实现很直观,无需多说。而迭代如何实现呢?


其实递归的本质是使用系统栈,那么迭代就是使用我们自己申请的栈,迭代的条件就是栈非空,而栈里放的是需要进行排序的数组或子数组的head以及长度len。


今天在网上看了一些代码,不得不吐槽一些人的代码习惯,各种 i  j   k  m n 等临时变量, 不懂得进行函数、功能拆分,不写注释,代码挤成一坨。


下面贴上我自己的,虽然写的也不咋地,但至少进行了代码拆分,写了详尽的注释,便于像我这样的初学者理解。由于拆了好几个函数出来,所以建议读者首先自行确认各个子函数的功能及其正确性。一旦确认,在接下来的阅读中只需把它当做一道目的明确的工序,不用再理会这道工序的具体流程。将代码放到Visual Studio里更有助于阅读。


#ifndef QUICKSORTRECU_H
#define QUICKSORTRECU_H


#define SIZE 20 // the size of the array need to be sorted



// Function: quickSortRecu
// Purpose: Sort elements in an array
// Inputs: T type pointer --- point to the head of the array
//               int len --- the length of the array
// Outputs: None
// Return: void

template <typename T>
void quickSortRecu(T array[], int len);



// Function: quickSortIter
// Purpose: Sort elements in an array
// Inputs: T type pointer --- point to the head of the array
//               int len --- the length of the array
// Outputs: None
// Return: void

template <typename T>
void quickSortIter(T array[], int len);




/
// Function: detach
// Purpose: Put all the elements less than the picked up value
//                   into the left part of the array, and put all the 
//                  elements larger than the picked up value into
//                   the right part of the array
// Inputs: T type pointer -- point to the head of the array
//               int len -- the length of the array
//              T type variable -- the picked up value for sorting
//               int type reference -- the head position of the middle part
// Outputs: None
// Return: void
/
template <typename T>
void detach(T array[], int len, T pkup, int &midHead, int &rightHead);






/
// Function: leftDetach
// Purpose: Put all the elements less than the picked up value
//                   into the left part of the array
// Inputs: T type pointer -- point to the head of the array
//               int len -- the length of the array
//               T type variable -- the picked up value for sorting
//               int type reference -- the head position of the middle part
// Outputs: None
// Return: void
/
template <typename T>
void leftDetach(T array[], int len, T pkup, int &midHead);




/
// Function: rightDetach
// Purpose: Put all the elements larger than the picked up value
//                   into the right part of the array
// Inputs: T type pointer -- point to the head of the array
//               int len -- the length of the array
//        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值