MOOC清华《面向对象程序设计》第3章编程题第1题:重载函数运算符以封装排序算法

请设计实现一个重载函数运算符的类,使用该类的对象可以完成对整数数组从大到小排序。示例:设该类对象名为obj,整数数组名为array,元素个数为N,则obj(array, N); 将修改array的内容,使其中的元素从大到小排序。(本题不计入总成绩) 提交要求:请将各个源文件(*.h, *.cpp)合并打印到一个PDF文件上传,要求各文件首行用注释说明文件名称。建议源代码中加上必要的注释,以便阅读。


//main.cpp
#include <iostream>
#include "Test.h"
using namespace std;

int main() {
	Test obj;
	int array[20] = {30,38,3,32,15,  1,41,47,59,80,  6,93,78,18,65,  60,51,22,17,31};
	obj(array, 20);
	return 0;
}

//Test.h
#ifndef Test_h
#define Test_h

class Test{
public:
	void operator() (int* array, int N);
};

#endif

//Test.cpp
#include <iostream>
#include "Test.h"
using namespace std;

void Test::operator() (int* array, int N){
	void QuickSort(int* array, int start, int end);
	void OutputOfArray(int* array, int n); 
	QuickSort(array, 0, N);
	OutputOfArray(array, N);
}

void QuickSort(int* array, int start, int end)  
{  
    if(start >= end - 1)   
        return;    
      
    int left = start, right = end;    
  
    int pivot = array[left];  
    int temp = 0;  
      
    for(int i = left + 1; i < right;   )    
    {  
        if(array[i] > array[left])  
        {  
            temp = array[left];  
            array[left] = array[i];  
            array[i] = temp;  
            left++;  
            i++;  
        }  
        else  
        {  
            temp = array[i];  
            for(int j = i; j < right; j++)  
                array[j] = array[j + 1];      
            array[right - 1] = temp;    
            right--;   
        }  
    }  
    array[left] = pivot;  
  
    QuickSort(array, start, left);  
    QuickSort(array, left + 1, end);  
} 

void OutputOfArray(int* array, int n)    
{    
    for(int i = 0; i < n; i++)    
        cout << array[i] << '\t';
	cout << endl;    
}  

测试结果:


  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值