ソートを挿入します.
1458 ワード
#include <iostream>
#include <typeinfo>
class InsertSort{
private:
int* array;
unsigned int theNumber;
public:
template<unsigned int N>
InsertSort(const int (&numbers)[N]);
~InsertSort();
void SortAndPrint();
};
template<unsigned int N>
InsertSort::InsertSort(const int (&numbers)[N])
:array(nullptr)
{
if(N == 0){
throw std::bad_cast();
}
this->theNumber = N;
this->array = new int[N];
for(int i=0; i<N; ++i){
this->array[i]=numbers[i];
}
std::cout<<"success"<<std::endl;
}
InsertSort::~InsertSort()
{
if(array != nullptr){
delete[] array;
}
this->array = nullptr;
}
void InsertSort::SortAndPrint()
{
for(int i =1; i<this->theNumber; ++i){
int tempValue = this->array[i]; // .
int j = i-1; //j=0;
std::cout<<"tempValue: "<<tempValue<<std::endl;
while(j >= 0 && this->array[j] > tempValue){ //array[0] array[1].
std::cout<<"j: "<<j<<" ";
std::swap(this->array[j+1], this->array[j]); // array[0] array[1] .
--j;
}
this->array[j+1] = tempValue;
}
}
int main()
{
int A[6]={5, 2, 4, 6, 1, 3};
InsertSort test(A);
test.SortAndPrint();
return 0;
}