直接插入排序--用面向对象的方法实现(简单)

源程序:

#include <iostream>

#define N 5

using namespace std;

class Insert

{

private:

int a[N];

public:

Insert(int m[], int n)     //构造函数初始化私有变量数组

{

for (int i = 0; i < n; i++)

a[i] = m[i];

}

void insert_sort();  //成员函数用于排序

void show();  //成员函数用于显示

};

void Insert::show()  //成员函数show()的定义

{

for (int i = 0; i < N; i++)

cout << a[i] << "  ";

}

void Insert::insert_sort()   //直接插入排序

{

int i, j, temp;

for (i = 1; i < N; i++)

{

temp = a[i];

j = i - 1;

while (j >= 0 && temp < a[j])

{

a[j + 1] = a[j];

j--;

}

a[j + 1] = temp;

}

}

int main()

{

int *pArray;

int i;

pArray = new int[N];  //动态分配数组

//向数组中输入5个整数

for (i = 0; i < N; i++)

cin >> pArray[i];

Insert B(pArray,N);  //类定义对象,并初始化对象

B.insert_sort();  //对象引用成员函数

B.show();   //对象引用成员函数

system("pause");

return 0;

}

运行结果:

原文地址:https://www.cnblogs.com/duanqibo/p/11972567.html