There is a bug in the following program of insertion sort, value of 'n' changes during the process of swapping 2 a[] elements in insertion(). I cannot understand why,...
Please help.
#include <iostream>
#include <cstdlib>
#include <time.h>
usingnamespace std;
class Aray{
public:
//int a[] incomplete type is not allowed
//I suspect that you have to specify the size of the array in class
//Dynamic variable works fine, though, as I write below
int n;
int *a ;
Aray(int n){
a = newint[n];
srand(time(0));
this->n = n;
for(int i = 0; i < n; i++)
{
a[i] = rand()%n + 1;
}
cout << "unsorted Array is: " << endl;
for (int i = 0; i < n; i++)
cout << a[i] << "\t";
}
//Do you need this destructor that does nothing?
~Aray(){}
void insertion()
{
for(int i = 0; i < n; i++)
{
int min = i;
for(int j = i; j < n; j++)
{
if(a[min] > a[j])
min = j;
}
int temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
void display()
{
for(int i = 0; i < n; i++)
{
cout << a[i] << "\t";
}
}
void tp()
{
cout << "number of elements: " << n << endl;
}
};
int main()
{
int n;
cout << "How many numbers do you want to sort?" << endl;
cin >> n;
Aray *b = new Aray(n);
//Why do you need this now that you have initialized the Aray with n?
b->n = n;
b->insertion();
b->tp();
cout << "\nThe sorted Array is: " << endl;
b->display();
return 0;
}