This question is not about where to put the srand function.
I have just started learning DSA with Insertion Sort. I have written a C++ program to perform Insertion Sort and wanted to create some neat visuals of the Time Analysis. I tried generating Random Arrays for the Time Analysis using the rand() function but the Arrays generated seem to have a character at the end. The elements in the character array should all be single digit integers like '0' '3' and so on.....
The Main Function of the Program:
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <iomanip>
using namespace std;
int size(char a[]) {
int l = 0;
while (a[l] != NULL) {
l++;
}
return l;
}
void InsertionSort(char arr[]) {
for (int k = 1; k < size(arr); k++) {
char temp = arr[k];
int i = k - 1;
while (i >= 0 && arr[i] > temp) {
arr[i + 1] = arr[i];
i--;
}
arr[i + 1] = temp;
}
}
int main(void) {
//Generate Random Arrays of size snum
for (int k = 1; k < 100; k++) {
int snum = k * 100;
char Array[snum];
srand(time(NULL));
for (int s = 0; s < snum; s++)
{
int no = rand() % 9 + 1;
Array[s] = no + '0';
}
cout << "START\t";
//cout<<"\n"<<Array<<"END\n"; // Character is being Printed at the end........ :-(
clock_t start, end;
start = clock();
InsertionSort(Array);
end = clock();
double time_taken = double(end - start) / double(CLOCKS_PER_SEC);
cout << "\"" << fixed << time_taken << setprecision(9) << "\",\"" << 100 * k << "\"" << endl;
}
}
How I Compile and Run the Program:
g++ InsertionSort.cpp
./a.out > InsertionSort.txt
--------------EDIT--------------
Based on the suggestions, I have replaced the Array with a vector. Please provide any further suggestions....
RandomIntVector.cpp
#include "RandomIntVector.h"
#include <random>
#include <vector>
using namespace std;
vector<int> RandomVector(int size){
uniform_int_distribution<> d(1, 1000);
mt19937 gen;
vector<int> Ar;
for(int s=0; s<(size-1); s++)
{
int no = d(gen);
Ar.push_back(no);
}
return Ar;}
InsertionSort.cpp
#include "InsertionSort.h"
#include <vector>
using namespace std;
void InsertionSort(vector<int> arr){
int size=arr.size();
for(int k=1;k<size;k++){
int temp = arr[k];
int i=k-1;
while(i>=0 && arr[i]>temp ){
arr[i+1]=arr[i];
i--;
}
arr[i+1]=temp;
}
}
Main.cpp
#include <iostream>
#include <vector>
#include <chrono>
#include <iomanip>
#include "RandomIntVector.h"
#include "InsertionSort.h"
using namespace std;
int main(void){
//Generate Random Arrays of size snum
for(int k=1;k<100;k++){
vector<int> Array = RandomVector(100*k);
clock_t start, end;
start = clock();
InsertionSort(Array);
end = clock();
double time_taken = double(end - start) /
double(CLOCKS_PER_SEC);
//Print the Time Taken along with the size of the Input
cout<<"\""<<fixed << time_taken << setprecision(9)<<"\",\""
<<100*k<<"\""<<endl;
}
return 0;
}