数组a中的n个元素已按升序排

作者在 2009-06-27 16:09:22 发布以下内容
若数组a中的n个元素已按升序排列,现将一个新数x插入到数组a中,插入后数组a的元素仍然保持升序。使用的插入排序算法是:从数组a的最后个元素开始,依次向前扫描数组元素,若a[i]大于x,则将a[i]放入a[i+1](后移一个位置),并继续向前扫描,直到找到某个a[i]小于或等于x,将x赋值到a[i+1]元素中,此时完成插入排序工作。编写程序时,要考虑初始时数组是空数组(即数组中没有元素),插入第一个元素时,要作特殊处理。试建立一个类InsSort,完成插入排序工作。
具体要求如下:
(1)私有数据成员。
●int n:数组实际元素的个数。
●int a[100]:存放排好序的整型序列。
(2)公有成员函数。
●InsSort(int b[ ], int size):构造函数,用参数b初始化a数组,用参数size初始化n,缺省值是0。
●void insert( int x):将x插入到数组a中。
●void show(fstream &):输出数组元素个数及数组中各元素值。
(3)在主程序中完成对该类进行测试。定义数组int b[100],其输入的初值是{1, 3, 5}。定义一个InsSort类的对象arr,用数组b及其元素个数初始化该对象。定义数组int c[100],其输入的初值是{0, 1, 2, 3, 5, 8, 10}。然后循环将数组c中的所有元素依次插入到对象arr的成员数组a中。最后输出对象arr中的全体数据成员。程序正确运行后,应输出:
number = 10  
0, 1, 1, 2, 3, 3, 5, 5, 8, 10
 
#include<iostream>
using namespace std;
class InsSort{
public:

    InsSort(int b[],int size);
    ~InsSort();
    void insert(int x);
    void show();
private:
    int n;
    int a[100];
};
InsSort::InsSort(int b[],int size){

    //memcpy( a, b, size);
    for(int i=0;i<size;i++){
    a[i]=*(b+i);
        }
    n=size;

}
InsSort::~InsSort(){

}
void InsSort::insert(int x){
    printf("wuyun.........x=%d\n",x);

for(int i=n-1;i>=0;i--){
    
    if(a[i]>x){
    a[i+1]=a[i];
    }
    else{
    a[i+1]=x;
    break;
    }
    if(i==0){if(a[i]>x)a[i]=x;}
}
++n;
show();

}
void InsSort::show(){


for(int i=0;i<n;i++){
    printf("wuyun.........a[%d]=%d\n",i,a[i]);

cout<<a[i]<<endl;
}
}
int main(){
    
    int b[100]={1,3,5};
    InsSort arr(b,3);

    int c[100]={0,1,2,3,5,8,10};
    for(int i=0;i<7;i++)
    {
        arr.insert(c[i]);
        
    }
    arr.show();
    return 0;
}
默认分类 | 阅读 4140 次
文章评论,共0条
游客请输入验证码
文章分类