递归实现很直观,无需多说。而迭代如何实现呢?
其实递归的本质是使用系统栈,那么迭代就是使用我们自己申请的栈,迭代的条件就是栈非空,而栈里放的是需要进行排序的数组或子数组的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
//