实现对一维整型数组的排序

【问题描述】试定义一个类ARRAY,实现对一维整型数组的排序。排序的规则如下:将一维数组中各元素按其各位的数字之和从小到大排序。具体要求如下:

    (1)私有数据成员:

        int a[100]; 待排序的数组;

        int n; 数组中元素的个数;

    (2)公有成员函数

       ARRAY(int t[], int m); 构造函数,利用参数t初始化成员a,参数m为数组t中元素的个数,用参数m初始化成员n;

        int sum(int x); 求整数x的各位数字之和,并返回该值,此函数供成员函数fun()调用;

       void fun(); 按要求对数组a的元素排序;

        void print(); 输出数组a的所有元素。

    (3)在主函数中对该类进行测试。

【输入形式】无
【输出形式】排序前后的数组对象中的数据。
【样例输入】无
【样例输出】

排序前:297 735 624 158 312 900

排序后:312 900 624 158 735 297

#include <iostream>
using namespace std;

class ARRAY {
	private:
		int a[100];
		int n;
	public:
		ARRAY(int t[], int m) {
			for (int i = 0; i < 100; i++) {
				a[i] = t[i];
			}
			n = m;
		}
		int sum(int x){
			int s=0;
			s=x/ 100 + x/ 10 % 10 + x% 100 % 10;
			return s;
		}
		void fun() {
			int temp;
			for(int i=0;i<n;i++){
				for(int j=0;j<n-1-i;j++){
					if(sum(a[j])>sum(a[j+1])){
						temp=a[j];
						a[j]=a[j+1];
						a[j+1]=temp;
					}
				}
			}
		}
		void print() {
			for (int i = 0; i < n; i++) {
				cout << a[i] << " ";
			}
			cout<<endl;
		}
};
int  main()        
{        int  a[]={297,735,624,158,312,900};
        ARRAY  arr(a,sizeof(a)/sizeof(int));
        cout<<"排序前:";  
        arr.print();
        arr.fun();
        cout<<"排序后:";
        arr.print  ();
        return  0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值