wtorek, 22 października 2024

Ascending and descending sorting - Example - class C++ Builder

 










New Unit:


File Class_Sorting.h


class multi_Sort

{

 private:

  int* tab_Date;

  int* min_Tab;

  int* max_Tab;

  int length;


 public:


multi_Sort(int size);

~multi_Sort();

void min_Sort(int *tab, int s);

void max_Sort(int* tab, int s);

void Load(int *tab);

int *min_Result();

     int *max_Result();

};

File Class_Sorting.cpp

#include "class_Sorting.h"

//---------------------------------------------------------------------------

#pragma package(smart_init)

multi_Sort::multi_Sort(int size)

{

length=size;

tab_Date=new int[length];

min_Tab=new int[length];

max_Tab=new int[length];

}


multi_Sort::~multi_Sort()

{

delete max_Tab;

delete min_Tab;

delete tab_Date;

}


void multi_Sort::min_Sort(int *tab, int s)

{

int i,j,k;

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

{

j=i;

k=tab[j];

while((j>0) && (tab[j-1]>k))

{

tab[j]=tab[j-1];

j--;

}

tab[j]=k;

}

}


void multi_Sort::max_Sort(int* tab, int s)

{

int i,j,k;

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

{

j=i;

k=tab[j];

while((j>0) && (tab[j-1]<k))

{

tab[j]=tab[j-1];

j--;

}

tab[j]=k;

}

}

void multi_Sort::Load(int *tab)

{

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

{

tab_Date[i]=min_Tab[i]=max_Tab[i]=tab[i];

}


}

int* multi_Sort::min_Result()

{

  min_Sort(min_Tab,length);

  return min_Tab;

}

int* multi_Sort::max_Result()

{

  max_Sort(max_Tab,length);

  return max_Tab;

}

Main Project:


#include <vcl.h>

#include <stdlib.h>

#include <time.h>

#pragma hdrstop


#include "p_Example.h"

#include "class_Sorting.h"

//---------------------------------------------------------------------------

#pragma package(smart_init)

#pragma resource "*.dfm"

TForm1 *Form1;

//---------------------------------------------------------------------------

__fastcall TForm1::TForm1(TComponent* Owner)

: TForm(Owner)

{

}

//---------------------------------------------------------------------------

void __fastcall TForm1::FormCreate(TObject *Sender)

{

 srand(time(NULL));

 Button1->Caption="&RUN";

}

//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)

{

  #define ssize 10

  #define mmax 100

  int j;

  int* main_Date=new int[ssize];

  int* min_Date=new int[ssize];

  int* max_Date=new int[ssize];

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

  {


  j=1+rand()%mmax;

  main_Date[i]=j;

  }

  multi_Sort my_Class(ssize);

  my_Class.Load(main_Date);

  min_Date=my_Class.min_Result();

  max_Date=my_Class.max_Result();

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

  {

  StringGrid1->Cells[i][0]=IntToStr(main_Date[i]);

  StringGrid1->Cells[i][1]=IntToStr(min_Date[i]);

      StringGrid1->Cells[i][2]=IntToStr(max_Date[i]);

  }

  delete max_Date;

  delete min_Date;

  delete main_Date;

}