如何实现快速排序(QuickSort)中间步骤的打印逻辑
解决快速排序中间步骤展示的问题
很容易实现!我们只需要添加一个数组打印的辅助函数,然后在每轮分区(partition)完成后触发打印即可。下面是修改后的完整代码,我会标注关键改动点:
修改后的完整代码
#include <cstdlib> #include <iostream> #include <string> using namespace std; // 新增:辅助函数,格式化打印数组 void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { if (i > 0) cout << ", "; cout << arr[i]; } cout << endl; } void quick_sort(int C[],int low,int high, int & quick_count, int& iteration, int arraySize); void partition ( int C[], int low, int high, int &m, int &n, int & quick_count ); void swap(int* a, int* b); int main() { int num_of_items; int quick_count = 0; int iteration = 0; // 新增:迭代计数器 cout<<"Enter The Number Of Elements To Be Sorted: "; cin>>num_of_items; int quick[num_of_items]; for(int i=0;i<num_of_items;i++) { cout<<"Element "<<i<<": "; cin>>quick[i]; } cout<<endl; // 调整:按期望格式打印初始数组 cout << "初始数组:"; printArray(quick, num_of_items); cout<<"----------------------------------------"<<endl<<endl; quick_sort(quick,0,num_of_items-1, quick_count, iteration, num_of_items); // 调整:按期望格式打印最终排序数组 cout << "最终排序数组:"; printArray(quick, num_of_items); cout<<"Quick sort count: "<<quick_count<<endl; } // 修改:新增迭代计数器和数组长度参数 void quick_sort (int C[], int low, int high, int & quick_count, int& iteration, int arraySize ) { int m, n; if ( low < high ) { partition ( C, low, high, m, n, quick_count ); // 新增:每完成一轮partition(迭代)后打印当前数组状态 iteration++; cout << "迭代" << iteration << ":"; printArray(C, arraySize); quick_sort ( C, low, m, quick_count, iteration, arraySize ); quick_sort ( C, n, high, quick_count, iteration, arraySize ); } } void partition ( int C[], int low, int high, int &m, int &n, int & quick_count) { int pivot = C[low]; int lastS1 = low - 1; int firstU = low; int firstS3 = high + 1; while ( firstU < firstS3 ) { quick_count++; if ( C[firstU] < pivot ) // S1 { ++lastS1; swap ( C[firstU],C[lastS1] ); ++firstU; } else if ( C[firstU] == pivot ) // S2 {++firstU;} else // C[firstU] > pivot // S3 { --firstS3; swap ( C[firstU], C[firstS3] ); } } m = lastS1; n = firstS3; } void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; }
关键改动说明
- 新增
printArray函数:专门负责格式化打印数组,用逗号分隔元素,符合你想要的输出样式。 - 迭代计数器:在
main里初始化iteration变量,通过引用传递给quick_sort,确保递归过程中能持续累加迭代次数。 - 修改
quick_sort参数:加入迭代计数器和数组长度,这样在递归过程中可以随时打印整个数组的状态。 - 触发打印的时机:在每次
partition执行完成后(也就是一轮迭代结束),立即打印当前数组,完美匹配你“每轮迭代后展示进展”的需求。 - 格式调整:把原来的无序/有序数组打印逻辑改成你期望的“初始数组:xxx”“最终排序数组:xxx”格式。
运行这个代码后,输入你示例中的6个元素,就能得到和你期望一致的输出啦!
内容的提问来源于stack exchange,提问作者aryashah2k
相关产品推荐
相关产品推荐

