Sorting an array diagonally - c++

I've looked up some websites but I couldn't find an answer to my problem.
Here's my code:
#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <time.h>
#include<iomanip>
#include<array>
#include <algorithm>
using namespace std;
const int AS = 6;
int filling(void);
void printing(int[AS][AS]);
int forsorting(int[][AS], int);
int main()
{
int funny = 0;
int timpa = 0;
int counter = 0;
int Array[AS][AS];
srand(time(0));
for (int i = 0; i<AS; i++)
{
for (int j = 0; j<AS; j++)
Array[i][j] = filling();
}
cout << "The unsorted array is" << endl << endl;
printing(Array);
cout << "The sorted array is" << endl << endl;
for (int il = 0; il<AS; il++)
{
for (int elle = 0; elle<AS; elle++)
Array[il][elle] =forsorting(Array, funny);
printing(Array);
}
system("PAUSE");
return 0;
}
int filling(void)
{
int kira;
kira = rand() % 87 + 12;
return kira;
}
void printing(int Array[AS][AS])
{
int counter = 0;
for (int i = 0; i<AS; i++)
{
for (int j = 0; j<AS; j++)
{
cout << setw(5) << Array[i][j];
counter++;
if (counter%AS == 0)
cout << endl << endl;
}
}
}
int forsorting(int Array[AS][AS], int funny)
{
int c, tmp, x;
int dice = 0;
int Brray[AS*AS];
int timpa = 0;
int super = 0;
//Transofrming Array[][] into Brray[]
for (int i = 0; i < AS; i++)
{
for (int k = 0; k < AS; k++)
{
Brray[timpa] = Array[i][k];
timpa++;
}
}
//Bubble sorting in Brray[]
for (int passer = 1; passer <= AS-1; passer++)
{
for (int timon = 1; timon <= AS-1; timon++)
{
if (Brray[timpa]>Brray[timpa + 1])
{
super = Brray[timpa];
Brray[timpa] = Brray[timpa + 1];
Brray[timpa + 1] = super;
}
}
}
//Transforming Brray[] into Array[][]
for (int e = 0; e<AS; e++)
{
for (int d = 0; d<AS; d++)
{
Brray[dice] = Array[e][d];
dice++;
}
}
***There's a part missing here***
}
What I have to do is, write a program using 3 functions.
The 1st function would fill my 2D array randomly (no problem with this part)
the 2nd function would print the unsorted array on the screen (no problem with this part)
and the 3rd function would sort my array diagonally as shown in this picture:
Then I need to call the 2nd function to print the sorted array. My problem is with the 3rd function I turned my 2D array into a 1D array and sorted it using Bubble sorting, but what I can't do is turn it back into a 2D array diagonaly sorted.

If you can convert from a 2D array to a 1D array, then converting back is the reverse process. Take the same loop and change around the assignment.
However in your case the conversion itself is wrong. It should take indexes in the order (0;0), (0;1), (1;0). But what it does is take indexes in the order (0;0), (0;1), (1;1).
My suggestion is to use the fact that the sum of the X and Y coordinates on each diagonal is the same and it goes from 0 to AS*2-2.
Then with another loop you can check for all possible valid x/y combinations. Something like this:
for ( int sum = 0; sum < AS*2-1; sum++ )
{
for ( int y = sum >= AS ? sum-AS+1 : 0; y < AS; y++ )
{
x = sum - y;
// Here assign either from Array to Brray or from Brray to Array
}
}
P.S. If you want to be really clever, I'm pretty sure that you can make a mathematical (non-iterative) function that converts from the index in Brray to an index-pair in Array, and vice-versa. Then you can apply the bubble-sort in place. But that's a bit more tricky than I'm willing to figure out right now. You might get extra credit for that though.
P.P.S. Realization next morning: you can use this approach to implement the bubble sort directly in the 2D array. No need for copying. Think of it this way: If you know a pair of (x;y) coordinates, you can easily figure out the next (x;y) coordinate on the list. So you can move forwards through the array from any point. That is all the the bubble sort needs anyway.

Suppose you have a 0-based 1-dimensional array A of n = m^2 elements. I'm going to tell you how to get an index into A, given and a pair of indices into a 2D array, according to your diagonalization method. I'll call i the (0-based) index in A, and x and y the (0-based) indices in the 2D array.
First, let's suppose we know x and y. All of the entries in the diagonal containing (x,y) have the same sum of their coordinates. Let sum = x + y. Before you got to the diagonal containing this entry, you iterated through sum earlier diagonals (check that this is right, due to zero-based indexing). The diagonal having sum k has a total of k + 1 entries. So, before getting to this diagonal, you iterated through 1 + 2 + ... + (sum - 1) entries. There is a formula for a sum of the form 1 + 2 + ... + N, namely N * (N + 1) / 2. So, before getting to this diagonal, you iterated through (sum - 1) * sum / 2 entries.
Now, before getting to the entry at (x,y), you went through a few entries in this very diagonal, didn't you? How many? Why, it's exactly y! You start at the top entry and go down one at a time. So, the entry at (x,y) is the ((sum - 1) * sum / 2 + y + 1)th entry, but the array is zero-based too, so we need to subtract one. So, we get the formula:
i = (sum - 1) * sum / 2 + y = (x + y - 1) * (x + y) / 2 + y
To go backward, we want to start with i, and figure out the (x,y) pair in the 2D array where the element A[i] goes. Because we are solving for two variables (x and y) starting with one (just i) and a constraint, it is trickier to write down a closed formula. In fact I'm not convinced that a closed form is possible, and certainly not without some floors, etc. I began trying to find one and gave up! Good luck!
It's probably correct and easier to just generate the (x,y) pairs iteratively as you increment i, keeping in mind that the sums of coordinate pairs are constant within one of your diagonals.

Store the "diagonally sorted" numbers into an array and use this to display your sorted array. For ease, assume 0-based indexing:
char order[] = { 0, 1, 3, 6, 10, 2, 4, 7, 11, 15, .. (etc)
Then loop over this array and display as
printf ("%d", Array[order[x]]);
Note that it is easier if your sorted Array is still one-dimensional at this step. You'd add the second dimension only when printing.

Following may help you:
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <vector>
template<typename T>
class DiagArray
{
public:
DiagArray(int size) : width(size), data(size * size), orders(size * size)
{
buildTableOrder(size);
}
const T& operator() (int x, int y) const { return data[orders[width * y + x]]; }
T& operator() (int x, int y) { return data[orders[width * y + x]]; }
void sort() { std::sort(data.begin(), data.end()); }
void display() const {
int counter = 0;
for (auto index : orders) {
std::cout << std::setw(5) << data[index];
counter++;
if (counter % width == 0) {
std::cout << std::endl;
}
}
}
private:
void buildTableOrder(int size)
{
int diag = 0;
int x = 0;
int y = 0;
for (int i = 0; i != size * size; ++i) {
orders[y * size + x] = i;
++y;
--x;
if (x < 0 || y >= size) {
++diag;
x = std::min(diag, size - 1);
y = diag - x;
}
}
}
private:
int width;
std::vector<T> data;
std::vector<int> orders;
};
int main(int argc, char *argv[])
{
const int size = 5;
DiagArray<int> da(size);
for (int y = 0; y != size; ++y) {
for (int x = 0; x != size; ++x) {
da(x, y) = size * y + x;
}
}
da.display();
std::cout << std::endl;
da.sort();
da.display();
return 0;
}

Thank you for your assistance everyone, what you said was very useful to me. I actually was able to think about clearly and came up with a way to start filling the array based on your recommendation, but one problem now, Im pretty sure that my logic is 99% right but there's a flaw somewhere. After I run my code the 2nd array isnt printed on the screen. Any help with this?
#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <time.h>
#include<iomanip>
#include<array>
#include <algorithm>
using namespace std;
const int AS = 5;
int filling(void);
void printing(int[AS][AS]);
int forsorting(int[][AS], int);
int main()
{
int funny = 0;
int timpa = 0;
int counter = 0;
int Array[AS][AS];
srand(time(0));
for (int i = 0; i<AS; i++)
{
for (int j = 0; j<AS; j++)
Array[i][j] = filling();
}
cout << "The unsorted array is" << endl << endl;
printing(Array);
cout << "The sorted array is" << endl << endl;
for (int il = 0; il<AS; il++)
{
for (int elle = 0; elle<AS; elle++)
Array[il][elle] =forsorting(Array, funny);
}
printing(Array);
system("PAUSE");
return 0;
}
int filling(void)
{
int kira;
kira = rand() % 87 + 12;
return kira;
}
void printing(int Array[AS][AS])
{
int counter = 0;
for (int i = 0; i<AS; i++)
{
for (int j = 0; j<AS; j++)
{
cout << setw(5) << Array[i][j];
counter++;
if (counter%AS == 0)
cout << endl << endl;
}
}
}
int forsorting(int Array[AS][AS], int funny)
{int n;
int real;
int dice = 0;
int Brray[AS*AS];
int timpa = 0;
int super = 0;
int median;
int row=0;
int col=AS-1;
//Transofrming Array[][] into Brray[]
for (int i = 0; i < AS; i++)
{
for (int k = 0; k < AS; k++)
{
Brray[timpa] = Array[i][k];
timpa++;
}
}
//Bubble sorting in Brray[]
for (int passer = 1; passer <= AS-1; passer++)
{
for (int timon = 1; timon <= AS-1; timon++)
{
if (Brray[timpa]>Brray[timpa + 1])
{
super = Brray[timpa];
Brray[timpa] = Brray[timpa + 1];
Brray[timpa + 1] = super;
}
}
}
//Transforming Brray[] into sorted Array[][]
for(int e=4;e>=0;e--)//e is the index of the diagonal we're working in
{
if(AS%2==0)
{median=0.5*(Brray[AS*AS/2]+Brray[AS*AS/2-1]);
//We start filling at median - Brray[AS*AS/2-1]
while(row<5 && col>=0)
{real=median-Brray[AS*AS/2-1];
Array[row][col]=Brray[real];
real++;
col--;
row++;}
}
else {
median=Brray[AS*AS/2];
//We start filling at Brray[AS*AS/2-AS/2]
while(row<5 && col>=0)
{real=Brray[AS*AS/2-AS/2];
n=Array[row][col]=Brray[real];
real++;
col--;
row++;}
}
}
return n;
}
Thanks again for your assistance

Related

How do I print out the occurences of each element in an area specified by a bounding box of a 2d matrix?

void searchValidEntries(int arr[101][101], int XL, int YL, int XH, int YH){
int sizeX = (XL - XH) + 1;
int sizeY = (YH - YL) + 1;
for (int i = XH; i < XH + sizeX; i++ ){
for (int j = YL; j < YL + sizeY; j++){
cout << arr[i][j] << ' ';
}
}
}
In the above code, I'm looping through a bounding box in a 2d array.
The coordinates of the array to be assigned a bounding box and the array itself are included as parameters in a function : int arr[101][101], int XL, int YL, int XH, int YH
The commented code cout << arr[i][j] << ' '; prints out the elements in the designated bounding box and I've run it so I know it actually prints out.
However, I want to get the frequency of each element in the bounding box, with the exception of 0, to be printed out.
I'm assuming that the required code will go in the for loop but I have no idea to start as I'm now learning all the semantics of C++.
I'm expecting an output of something like:
5 --> 3
83 --> 2
23 --> 9
There are multiple ways to do this. I suggest using a vector< pair< int, int >>.
Each element of this vector holds two things:
1- a value that has been visited
2- the occurrence of this value
I've added some comments to my code to clarify this method.
#include <iostream>
using namespace std;
#include <vector>
void searchValidEntries(int arr[101][101], int XL, int YL, int XH, int YH) {
vector<pair<int, int>> holder_vec;
int sizeX = (XL - XH) + 1;
int sizeY = (YH - YL) + 1;
for (int i = XH; i < XH + sizeX; i++) {
for (int j = YL; j < YL + sizeY; j++) {
bool thisElementIsNew = true; // By default, it's the first occurence of this element.
for (auto& it : holder_vec) { // Iterate the vector of previously considered elements and chekc this target value.
if (it.first == arr[i][j]) {
it.second++; // Increase the occurence of this element by one.
thisElementIsNew = false; // This value has been previously visited.
break; // Stop iterating vector
}
}
if (thisElementIsNew) { // Add a new pair to holder_vec;
const pair<int, int> newPair(arr[i][j], 1); // newPair.first = The value of this element. // newPair.second = the occurence of this value.
holder_vec.push_back(newPair);
}
}
}
// Print result:
for (const auto& it : holder_vec) {
cout << it.first << " ---> " << it.second << endl;
}
}

Trying to implement Durand-Kerner-Method in C++ using Matrices

My implementation of the Durand-Kerner-Method (https://en.wikipedia.org/wiki/Durand%E2%80%93Kerner_method) does not seem to work. I believe (see following code) that I am not calculating new approximation correctly in the algorithm part itself. I cannot seem to be able to fix the problem. Very grateful for any advice.
#include <complex>
#include <cmath>
#include <vector>
#include <iostream>
#include "DurandKernerWeierstrass.h"
using namespace std;
using Complex = complex<double>;
using vec = vector<Complex>;
using Matrix = vector<vector<Complex>>;
//PRE: Recieves input value of polynomial, degree and coefficients
//POST: Outputs y(x) value
Complex Polynomial(vec Z, int n, Complex x) {
Complex y = pow(x, n);
for (int i = 0; i < n; i++){
y += Z[i] * pow(x, (n - i - 1));
}
return y;
}
/*PRE: Takes a test value, degree of polynomial, vector of coefficients and the desired
precision of polynomial roots to calculate the roots*/
//POST: Outputs the roots of Polynomial
Matrix roots(vec Z, int n, int iterations, const double precision) {
Complex z = Complex(0.4, 0.9);
Matrix P(iterations, vec(n, 0));
Complex w;
//Creating Matrix with initial starting values
for (int i = 0; i < n; i++) {
P[0][i] = pow(z, i);
}
//Durand Kerner Algorithm
for (int col = 0; col < iterations; col++) {
*//I believe this is the point where everything is going wrong*
for (int row = 0; row < n; row++) {
Complex g = Polynomial(Z, n, P[col][row]);
for (int k = 0; k < n; k++) {
if (k != row) {
g = g / (P[col][row] - P[col][k]);
}
}
P[col][row] -= g;
}
return P;
}
}
The following Code is the code I am using to test the function:
int main() {
//Initializing section
vec A = {1, -3, 3,-5 };
int n = 3;
int iterations = 10;
const double precision = 1.0e-10;
Matrix p = roots(A, n, iterations,precision);
for (int i = 0; i < iterations; i++) {
for (int j = 0; j < n; j++) {
cout << "p[" << i << "][" << j << "] = " << p[i][j] << " ";
}
cout << endl;
}
return 0;
}
Important to note the Durand-Kerner-Algorithm is connected to a header file which is not included in this code.
Your problem is that you do not transcribe the new values into the next data record with index col+1. Thus in the next loop you start again with a data set of zero entries. Change to
P[col+1][row] = P[col][row] - g;
If you want to use the new improved approximation immediately for all following approximations, then use
P[col+1][row] = (P[col][row] -= g);
Then the data sets all contain the next approximations, especially the first one will no longer contain the initially set powers.

Retrieve index of element of array stored in vector

I have a 2D array used to store non-repeated values and some entries are randomly picked and push_back-ed into a vector as favorite list.
int num[10][10];
vector<int> fav_list;
int retrieved_i, retrieved_j, retrieve_vector_position;
for(i=0;i<10;i++) for(j=0;j<10;j++)
// ...assign numbers to num...
fav_list.push_back(num[2][3]);
fav_list.push_back(num[4][7]);
fav_list.push_back(num[6][2]);
//...push_back more random selected num[...][...] into fav_list...
The problem is, how can I retrieve the i, j index of particular fav_list[...]?
I've tried to make struct struct Num{int value, index_i, index_j;}num[10][10]; so that I can do in this way
retrieved_i = fav_list[retrieve_vector_position].index_i;
retrieved_j = fav_list[retrieve_vector_position].index_j;
but I wish to know is there any other better/ efficient ways?
Using a plain vector to store your 2D array would solve the problem. You could access elements in the vector by calculating absolute index (i * row_len + j) and store in fav_list absolute indices.
Also, you may want to use std::unordered_map for fav_list. Generally, hash tables is the most efficient data structure for such caches.
There are a few possibilities depending on how often you want to access the i & j indices / the favorite number itself.
One approach is, to save the indices instead of the number (or additional to it). With this approach, more memory is required but the the time to access the indices will be constant, regardless how big your array becomes. This uses std::pair to store 2 elements in your favorite vector.
#include <vector>
#include <iostream>
#include <utility>
using namespace std;
int main(int argc, char* argv[]) {
int num[10][10];
vector<std::pair<int, int>> fav_list;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (/* your condition for favorites */) {
fav_list.push_back(num[i][j]);
}
}
}
/* example get the indices of the first favorite */
cout << "i: " << fav_list[0].first << "j: " << fav_list[0].second << endl;
/* example get the first favorite */
cout << num[fav_list[0].first][fav_list[0].second] << endl;
return 0;
}
Another approach is to "lookup" the indices, when you require it: it has the condition, that one number is not multiple times contained in your num[][] array (otherwise the first entry is found). There is no additional memory overhead required, but the time to lookup the indices will increase when your array gets bigger.
#include <vector>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
int num[10][10];
vector<int> fav_list;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (/* your condition for favorites */) {
fav_list.push_back(num[i][j]);
}
}
}
/* example get the indices of the first favorite */
int indexI = -1, indexJ = -1;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (fav_list[0] == num[i][j]) {
indexI = i;
indexJ = j;
break;
}
}
}
cout << "i: " << indexI << "j: " << indexJ << endl;
/* example get the first favorite */
cout << fav_list[0] << endl;
return 0;
}
Instead of storing 3 variable value, x and y just store a single unsigned int via which you can retrieve x and y.
struct fav_list
{
unsigned int total_rows;
unsigned int total_columns;
fav_list(unsigned int _rows, unsigned int _columns)
{
total_rows = _rows;
total_columns = _columns;
}
unsigned int get_x(unsigned int _index)
{
return v[_index] / total_columns;
}
unsigned int get_y(unsigned int _index)
{
return v[_index] % total_columns;
}
void append_xy_to_list(unsigned int _x, unsigned int _y)
{
v.push_back(_x * total_columns + _y);
}
vector <unsigned int> v;
};
fav_list f(10, 10);
for(x = 0; x < 10; ++x)
{
for(y = 0; y < 10; ++y)
{
//suppose you want to store the indexes of element num[x][y] then:
f.append_xy_to_list(x, y);
}
}
retrieved_i = f.get_x(retrieve_vector_position);
retrieved_j = f.get_y(retrieve_vector_position);

filling my array with random values C++

I'm trying to make a simple battle ship game. I'm stuck on trying to randomly place the ships on my board.I have a feeling it is because I should be using a vector instead of an array. but I'm not sure how to create a 2d vector.
Here's what I have so far:
using namespace std;
void clearBoard(const int row, const int col)
{
int grid[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col;j++) {
grid[i][j] = 0;
cout << grid[i][j] << " ";
}
cout << endl;
}
}
void setShips(int max_ships1, int row, int col)
{
int ship_counter = 0;
while(ship_counter < max_ships1) {
int x = rand() % row;
int y = rand() % col;
int matrix[x][y]
if (matrix[x][y] != 1) {
ship_counter++;
matrix[x][y] = 1;
cout << matrix[x][y] << " ";
}
cout << endl;
}
}
int main(int argc, char* argv[])
{
int _row = atoi(argv[0]);
int _col = atoi(argv[2]);
int max_ships;
if (_row > _col) {
max_ships = _row;
}
else if (_col > _row) {
max_ships = _col;
}
else {
max_ships = _row;
}
cout << "enter the size of the board:";
cin >> _row >> _col;
clearBoard(_row, _col);
setShips(_row,_col,max_ships);
return 0;
}
If the user decides on a 3x3 board, the first function returns:
0 0 0
0 0 0
0 0 0
I'm hoping to randomly generate 1's to represent a battleship's position.
Here's an example on a 3x3 board:
1 0 0
0 1 0
1 0 0
Thanks.
Your main problem is that grid goes out of scope (and is effectively deleted) when clearBoard returns, and matrix (a completely unrelated array to grid) goes out of scope each time through your while loop. That means that you're filling grid with zeroes, then creating a bunch of other arrays with random data and sometimes setting one element to 1. You need to either make grid global, or return it from clearBoard and pass it to setShips as an argument.
Passing around multidimensional raw arrays is kind of complicated, so using a vector might make this a bit easier for you if you don't want to make the array global. To create a two-dimensional vector, you might think that std::vector<std::vector<int>> will work, but that's not quite right. You can do it that way, as mentioned in the comments, but technically, std::vector<std::vector<int>> is what's called a jagged array, meaning that you can have each row be a different length - unlike your raw 2D array, where you know that each row must always be the same length.
The proper way to make a two-dimensional array with a vector is this:
std::vector<int> grid(row * col);
grid[i * row + j] = 1; // Or i * col + j will also work.
As you can see, it's a bit more complicated to get an element out by its (x,y) coordinates. It doesn't matter which of the two calculation methods you use, but in one version i is x and j is y, while in the other, the reverse is true (i is y, etc).
You can also set up a 2D vector like this :
#include<vector>
#include<iostream>
using namespace std;
int main()
{
std::vector< std::vector<int> > grid2D;
//m * n is the size of the grid
int m = 10;
int n = 10;
//Grow rows by m
grid2D.resize(m);
//Grow Columns by n
for(int i = 0 ; i < m ; ++i) grid2D[i].resize(n);
// print out 2D grid on screen
for(i = 0 ; i < m ; ++i){
for(int j = 0 ; j < n ; ++j){
grid2D[i][j]=0;
cout<<""<<grid2D[i][j]<<" ";
}
cout<<"\n";
}
cout<<"\n";
return 0;
}

FirstChance Exception StackOverFlow Merge Sort Shell Sort Bubble Sort

Hey guys I'm working on some sorts and am trying to implement a bubble sort, a merge sort, and a shell sort. I use an outdated technique but I was wondering if you guys could let me know why I keep getting the following error:
First-chance exception at 0x01135EF7 in sortApplication2.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00542000).
Unhandled exception at 0x01135EF7 in sortApplication2.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00542000).
I am using Visual Studio 2012 if that plays any part. My code is in three different files so I'll post each separately.
My header file:
#pragma once
class sort
{
public:
sort();
void random1(int array[]);
void random2(int array[]);
void random3(int array[]);
void bubbleSort(int array[], int length);
/*void merge(int *input, int p, int r);
void merge_sort(int *input, int p, int r);*/
void shellSort(int array[], int length);
};
My class implementation file:
#include "sort.h"
#include <time.h>
#include <iostream>
using namespace std;
sort::sort()
{}
void sort::random1(int array[])
{
// Seed the random-number generator with current time so that
// the numbers will be different every time the program runs.
for(int i = 0; i < 25; i++)
{
srand ((unsigned) time(NULL));
int n = rand(); //generates a random number
array[i] = n; //places it into the array
}
}
void sort::random2(int array[])
{
// Seed the random-number generator with current time so that
// the numbers will be different every time the program runs.
for(int i = 0; i < 10000; i++)
{
srand ((unsigned) time(NULL));
int n = rand(); //generates a random number
array[i] = n; //places it into the array
}
}
void sort::random3(int array[])
{
// Seed the random-number generator with current time so that
// the numbers will be different every time the program runs.
for(int i = 0; i < 100000; i++)
{
srand ((unsigned) time(NULL));
int n = rand(); //generates a random number
array[i] = n; //places it into the array
}
}
void sort::bubbleSort(int array[], int length)
{
//Bubble sort function
int i,j;
for(i = 0; i < 10; i++)
{
for(j = 0; j < i; j++)
{
if(array[i] > array[j])
{
int temp = array[i]; //swap
array[i] = array[j];
array[j] = temp;
}
}
}
}
/*void sort::merge(int* input, int p, int r) //the merge algorithm of the merge sort
{
int mid = (p + r) / 2;
int i1 = 0;
int i2 = p;
int i3 = mid + 1;
// Temp array
int x = r -p + 1;
int *temp;
temp = new int [x];
// Merge in sorted form the 2 arrays
while ( i2 <= mid && i3 <= r )
if ( input[i2] < input[i3] )
temp[i1++] = input[i2++];
else
temp[i1++] = input[i3++];
// Merge the remaining elements in left array
while ( i2 <= mid )
temp[i1++] = input[i2++];
// Merge the remaining elements in right array
while ( i3 <= r )
temp[i1++] = input[i3++];
// Move from temp array to master array
for ( int i = p; i <= r; i++ )
input[i] = temp[i-p];
}
void sort::merge_sort(int *input, int p, int r) //the merge sort algorithm
{
if ( p < r ) //When p and r are equal the recursion stops and the arrays are then passed to the merge function.
{
int mid = (p + r) / 2;
merge_sort(input, p, mid); //recursively calling the sort function in order to break the arrays down as far as possible
merge_sort(input, mid + 1, r);//recursively calling the sort function in order to break the arrays down as far as possible
merge(input, p, r); //merge function realigns the smaller arrays into bigger arrays until they are all one array again
}
}*/
void sort::shellSort(int array[], int length) //Shell sort algorithm
{
int gap, i, j, temp;
for( gap = length / 2; gap > 0; gap /= 2) //gap is the number of variables to skip when doing the comparisons
{
for( i = gap; i < length; i++) //This for loop sets the variable to use as the gap for the comparisons
{
for (j = i - gap; j >= 0 && array[j] > array[j + gap]; j -= gap)
{
temp = array[j]; //the array variables are swapped
array[j] = array[j + gap];
array[j + gap] = temp;
}
}
}
}
And my driver file:
#include "sort.h"
#include <iostream>
using namespace std;
int main()
{
int bubbleArray1[25]; //these are the arrays to be sorted. three for each sort. each has a length of 25, 10000, or 100000.
int bubbleArray2[10000];
int bubbleArray3[100000];
int mergeArray1[25];
int mergeArray2[10000];
int mergeArray3[100000];
int shellArray1[25];
int shellArray2[10000];
int shellArray3[100000];
sort Sorts;
Sorts.random1(bubbleArray1);
Sorts.random1(mergeArray1);
Sorts.random1(shellArray1);
Sorts.random2(bubbleArray2);
Sorts.random2(mergeArray2);
Sorts.random2(shellArray2);
Sorts.random3(bubbleArray3);
Sorts.random3(mergeArray3);
Sorts.random3(shellArray3);
cout << "BubbleSort1 is now being sorted.\n";
Sorts.bubbleSort(bubbleArray1, 25);
cout << "BubbleSort2 is now being sorted.\n";
Sorts.bubbleSort(bubbleArray2, 10000);
cout << "BubbleSort3 is now being sorted.\n";
Sorts.bubbleSort(bubbleArray3, 100000);
cout << "End bubble sorts.\n";
/*cout << "MergeSort1 is now being sorted.\n";
Sorts.merge_sort(mergeArray1, 0, 25);
cout << "MergeSort2 is now being sorted.\n";
Sorts.merge_sort(mergeArray2, 0, 10000);
cout << "MergeSort3 is now being sorted.\n";
Sorts.merge_sort(mergeArray3, 0, 100000);
cout << "End merge sorts.\n";*/
cout << "ShellSort1 is now being sorted.\n";
Sorts.shellSort(shellArray1, 25);
cout << "ShellSort1 is now being sorted.\n";
Sorts.shellSort(shellArray2, 10000);
cout << "ShellSort1 is now being sorted.\n";
Sorts.shellSort(shellArray3, 100000);
cout << "End shell sorts.\n";
cout << "Array\tElements\n";
cout << "BubbleSort1\t";
for(int i = 0; i < 25; i++)
{
cout << bubbleArray1[i] << " ";
}
cout << "\nMergeArray1\t";
for(int i = 0; i < 25; i++)
{
cout << mergeArray1[i] << " ";
}
cout << "\nShellArray1\t";
for(int i = 0; i < 25; i++)
{
cout << shellArray1[i] << " ";
}
return 0;
}
I know it's a lot of code. And there are probably many ways I could make the code better.
I would just like to know what's causing the error up above since I can't find it using my compiler.
You are allocating too much memory on the stack. Variables with 'automatic' storage class go on the stack. Allocate heap instead.
So, instead of:
int shellArray3[100000];
Do:
int* shellArray3 = new int[100000];
Or better yet, use std::vector.
If you don't want to use heap memory, you could also use the static storage class for something like this. To do that:
static int shellArray3[100000];
That will allocate one instance of the variable for the whole program rather than allocating a copy for each function entry on the stack.