I'm making this program where I have to count the number of swaps and comparisons a quick sort function, and we have to pass the swaps and comps to the function. I'm not too sure how to do this. I have it so it can be done without passing anything to it, as shown below.
#include <iostream>
#include <ctime>
#include <stdlib.h>
#include <math.h>
using namespace std;
struct SwapandComp {
int swaps;
int comps;
};
const long ARRAY_SIZE = 5000;
int totalSwaps = 0;
int totalComps = 0;
int partition(int[], int, int) //add parameters int& swap and int& comp
SwapandComp quickSort(int[], int, int) //also add parameters for int& swap and int& comp
int main() {
SwapandComp qui;
long masterAry[ARRAY_SIZE] = {0};
int quickAry[ARRAY_SIZE] = {0};
int start = 0;
int end = 0;
double difference = 0;
int size = ARRAY_SIZE;
srand(time(NULL));
for (int i = 0; i < ARRAY_SIZE; i++) {
masterAry[i] = rand();
}
for (int a = 0; a < ARRAY_SIZE; a++) {
quickAry[a] = masterAry[a];
}
start = clock();
qui = quickSort(quickAry, 0, ARRAY_SIZE - 1);
end = clock();
difference = end - start;
double f = difference / CLOCKS_PER_SEC;
cout << "Quick: " << f << " " << qui.swaps << " " << qui.comps << endl;
}
This is the main. It's where values are assigned to the array to be sorted by the quickSort function, which will be defined below.
int partition(int numbers[], int i, int k) { //add parameters int& swap and int& comp
int l = 0;
int h = 0;
int midpoint = 0;
int pivot = 0;
int temp = 0;
bool done = false;
// Pick middle element as pivot
midpoint = i + (k - i) / 2;
pivot = numbers[midpoint];
l = i;
h = k;
while (!done) {
// Increment l while numbers[l] < pivot
while (numbers[l] < pivot) {
++l;
totalComps++;
}
// Decrement h while pivot < numbers[h]
while (pivot < numbers[h]) {
--h;
totalComps++;
}
// If there are zero or one elements remaining,
// all numbers are partitioned. Return h
if (l >= h) {
totalComps++;
done = true;
}
else {
// Swap numbers[l] and numbers[h],
// update l and h
temp = numbers[l];
numbers[l] = numbers[h];
numbers[h] = temp;
totalSwaps++;
++l;
--h;
}
}
//cout << totalSwaps << " " << totalComps << endl;
return h;
}
This is the partition function to find where to find the next partition point
SwapandComp quickSort(int numbers[], int i, int k) { //add parameters int& swap and int& comp
SwapandComp quick = { 0 };
//quick.swaps = quick.comps = 0;
int j = 0;
int z = 0;
// Base case: If there are 1 or zero elements to sort,
// partition is already sorted
if (i >= k) {
return quick;
}
// Partition the data within the array. Value j returned
// from partitioning is location of last element in low partition.
j = partition(numbers, i, k);
// Recursively sort low partition (i to j) and
// high partition (j + 1 to k)
quickSort(numbers, i, j);
quickSort(numbers, j + 1, k);
quick.swaps = totalSwaps;
quick.comps = totalComps;
//totalSwaps = 0;
//totalComps = 0;
return quick;
}
And finally, here is the quick sort function where all the swaps and comps will be added together and put into the struct. Again, I'm not too sure how to add in the pass by reference variables for swap and comp. Any help is appreciated! (Also sorry about the code formatting, it got kind of crazy on my screen.)
Related
So, I am writing a program in C++ that has a function in the Sort class that I wish to call in the Main class. The function has several data members used that are present in that class, that are not present in the Main class and I keep getting a C2660 error, that "Function does not take 0 arguments". Is there a way (short of writing a bunch of getters and setters) to resolve this?
#include "Sort.h"
#include "Timer.h"
using namespace std;
int main
{
Sort *sort = new Sort();
Timer ti;
sort->SetRandomSeed(12345);
sort->InitArray();
cout << "starting InsertionSort" << endl;
ti.Start();
sort->InsertionSort();
ti.End();
cout << "Insertion sort duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
//sort->InitList();
//cout << "starting InsertionSortList()" << endl;
//ti.Start();
//sort->InsertionSortList();
//ti.End();
//cout << "Insertion sort list duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
sort->InitArray();
cout << "starting SelectionSort" << endl;
ti.Start();
sort->SelectionSort();
ti.End();
cout << "SelectionSort duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
sort->InitArray();
cout << "starting MergeSort" << endl;
ti.Start();
sort->MergeSort();
ti.End();
cout << "MergeSort duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
sort->InitArray();
cout << "starting QuickSort" << endl;
ti.Start();
sort->QuickSort();
ti.End();
cout << "QuickSort duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
sort->InitVector();
cout << "starting std::sort() of Vector<int>" << endl;
ti.Start();
sort->VectorSort();
ti.End();
cout << "std::sort() duration: " << ti.DurationInNanoSeconds() << "ns" << endl;
delete sort;
cout << endl <<"Press [Enter] key to exit";
getchar();
}
Sort.cpp
//const int for array
int num = 10000000;
int val = 10000;
//array
int *tmpArray, *qArr, *insArr, *selArr, *mergArr = NULL;
int low, high;
//duration for timer
int duration = 0;
Sort::Sort()
{
}
Sort::~Sort()
{
}
void Sort::InitArray()
{
//int for index
int i = 0;
tmpArray = new int[num];
qArr = new int[num];
insArr = new int[num];
selArr = new int[num];
mergArr = new int[num];
//fill temp array with sequential numbers
for (int i = 0; i < num; i++)
{
tmpArray[i] = 1 + rand() % val;
}
for (i = 0; i < num; i++)
{
qArr[i] = tmpArray[i];
insArr[i] = tmpArray[i];
selArr[i] = tmpArray[i];
mergArr[i] = tmpArray[i];
}
low = qArr[0];
high = qArr[num - 1];
int n = sizeof(tmpArray) / sizeof(tmpArray[0]);
}
void Sort::InitVector()
{
vector<int> v(num);
std::generate(v.begin(), v.end(), std::rand);
}
void Sort::InitList()
{
// A set to store values
std::list<int> l;
// Loop until we get 50 unique random values
while (l.size() < num)
{
l.push_back(1 + rand() % val);
}
for (int n : l) {
std::cout << n << '\n';
}
}
//setting seed
void Sort::SetRandomSeed(unsigned int seed)
{
seed = rand();
}
void Sort::InsertionSort()
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = insArr[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && insArr[j] > key)
{
insArr[j + 1] = insArr[j];
j = j - 1;
}
insArr[j + 1] = key;
}
delete[] insArr;
insArr = NULL;
}
int Sort::partition(int qArr[], int low, int high)
{
int pivot = qArr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high - 1; j++)
{
// If current element is smaller than or
// equal to pivot
if (qArr[j] <= pivot)
{
i++; // increment index of smaller element
swap(&qArr[i], &qArr[j]);
}
}
swap(&qArr[i + 1], &qArr[high]);
return (i + 1);
}
void Sort::QuickSort(int qArr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(qArr, low, high);
// Separately sort elements before
// partition and after partition
QuickSort(qArr, low, pi - 1);
QuickSort(qArr, pi + 1, high);
}
delete[] qArr;
qArr = NULL;
}
void Sort::SelectionSort()
{
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < n - 1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i + 1; j < n; j++)
if (selArr[j] < selArr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
swap(&selArr[min_idx], &selArr[i]);
}
delete[] selArr;
selArr = NULL;
}
void Sort::swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void Sort::VectorSort()
{
std::sort(v.begin(), v.end());
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void Sort::merge(int mergArr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int* L;
int* R;
/* create temp arrays */
L = new int[n1];
R = new int[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = mergArr[l + i];
for (j = 0; j < n2; j++)
R[j] = mergArr[m + 1 + j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
mergArr[k] = L[i];
i++;
}
else
{
mergArr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
mergArr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
mergArr[k] = R[j];
j++;
k++;
}
}
void Sort::MergeSort(int mergArr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l + (r - l) / 2;
// Sort first and second halves
MergeSort(mergArr, l, m);
MergeSort(mergArr, m + 1, r);
merge(mergArr, l, m, r);
}
delete[] mergArr;
mergArr = NULL;
}
Sort.h
#include <iomanip>
#include <fstream>
#include <string>
#include <queue>
#include <stack>
#include <vector>
#include<iostream>
#include<cstdio>
#include<sstream>
#include<algorithm>
#include<list>
using namespace std;
#pragma once
class Sort
{
public:
Sort();
~Sort();
void InitArray();
void InitVector();
void InitList();
void SetRandomSeed(unsigned int seed);
int n, right, left, l, r, m;
vector<int> v;
void InsertionSort();
int partition(int qArr[], int low, int high);
void QuickSort(int qArr[], int low, int high);
void swap(int * xp, int * yp);
void VectorSort();
void MergeSort(int arr[], int l, int r);
void merge(int arr[], int l, int m, int r);
void SelectionSort();
};
Ignoring the Timer class (those are all good) here is the rest of the code. The C2660 errors are shown for the sort->MergeSort() and sort->QuickSort() calls in main.
I resolved the issues myself. I created helper functions in the Sort class that have no arguments and call the functions themselves to use in the main. Helper Functions shown below.
Sort.cpp
//method for Main to run to prevent C2660 errors
void Sort::mergeHelper()
{
MergeSort(mergArr, l, r);//call merge sort method
}
//method for Main to run to prevent C2660 errors
void Sort::quickHelper()
{
QuickSort(qArr, low, high);//call quick sort method
}
int Main
{
sort->quickHelper();
sort->mergeHelper();
}
Basic quicksort function that partitions and has myswap. everything works fine except for index 0 in the array.
#include<iostream>
#include<string>
#include<iostream>
#include<vector>
#include <ctime>
using namespace std;
//swap
void myswap(int mya[], int a, int b) {
int temp = mya[a];
mya[a] = mya[b];
mya[b] = temp;
}
//partition, returns pivot index
int mypartition(int mya[], int first, int last)
{
int middle = ((first + last) / 2);
int pivot = mya[middle];
//swap first with middle
myswap(mya, first, middle);
//two pointers
int pivotindex = first;
//loop through the elements
for (int index = first + 1; index <= last; index++) {
if (mya[index] <= pivot)
{
pivotindex++;
myswap(mya, pivotindex, index);
}
}
//swap the pivot in its right place
myswap(mya, first, pivotindex);
return pivotindex;
}
void QuickSort(int mya[], int a, int b)
{
//partition
if (a <= b)
{
int index = mypartition(mya, a, b);
QuickSort(mya, a, index - 1);
QuickSort(mya, index + 1, b);
}
}
int main() {
//vector<int> mya;
int * mya = new int[5000000];
srand(time(0));
int i = 0;
int last = 0;
while(i < 100)
{
int x = (rand() + time(0)) % 5000000;
mya[last] = x;
last++;
i++;
}
clock_t startTime, endTime;
startTime = clock();
QuickSort(mya, 0, last);
endTime = clock();
cout << "Sorted in " << (double)(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
for (int i = 0; i < 100; i++)
{
cout << mya[i] << endl;
}
delete[] mya;
return 0;
}
The problem im having is that the array gets sorted but when mya[0] is called in the for loop it outputs -842150451. This is just a basic quicksort and for some reason im having trouble with it.
You are calling it wrong.
QuickSort(mya, 0, last-1);
Remember that there are last elements, meaning they are indexed 0..last-1.
You do also have a potential overflow problem with your calculation of middle. Use (last - first + 1)/2 + first.
Hope this helps.
Integer Overflow Causing this problem.
int x = (rand() + time(0)) % 5000000;
this line sometime two 10 digits long numbers whose sum is causing the integer overflow.
Just modify that statement as following and your code starts working:
int x = (rand() % 5000000) + (time(0) % 5000000);
Edit: It was a problem I found executing your code using Ideone. Further noticing I found Your Index 0 problem is actually caused by partition function.
change for (int index = first + 1; index <= last; index++) { this line to
for (int index = first + 1; index < last; index++) { //remove the equal sign
N.B: for me this fixed your issue. But I think in your void QuickSort(int mya[], int a, int b)
if (a <= b) should be changed to if (a < b).
I need a way to solve the classic 5SUM problem without hashing or with a memory efficient way of hashing.
The problem asks you to find how many subsequences in a given array of length N have the sum equal to S
Ex:
Input
6 5
1 1 1 1 1 1
Output
6
The restrictions are:
N <= 1000 ( size of the array )
S <= 400000000 ( the sum of the subsequence )
Memory usage <= 5555 kbs
Execution time 2.2s
I'm pretty sure the excepted complexity is O(N^3). Due to the memory limitations hashing doesn't provide an actual O(1) time.
The best I got was 70 points using this code. ( I got TLE on 6 tests )
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#define MAX 1003
#define MOD 10472
using namespace std;
ifstream in("take5.in");
ofstream out("take5.out");
vector<pair<int, int>> has[MOD];
int v[MAX];
int pnt;
vector<pair<int, int>>::iterator it;
inline void ins(int val) {
pnt = val%MOD;
it = lower_bound(has[pnt].begin(), has[pnt].end(), make_pair(val, -1));
if(it == has[pnt].end() || it->first != val) {
has[pnt].push_back({val, 1});
sort(has[pnt].begin(), has[pnt].end());
return;
}
it->second++;
}
inline int get(int val) {
pnt = val%MOD;
it = lower_bound(has[pnt].begin(), has[pnt].end(), make_pair(val, -1));
if(it == has[pnt].end() || it->first != val)
return 0;
return it->second;
}
int main() {
int n,S;
int ach = 0;
int am = 0;
int rez = 0;
in >> n >> S;
for(int i = 1; i <= n; i++)
in >> v[i];
sort(v+1, v+n+1);
for(int i = n; i >= 1; i--) {
if(v[i] > S)
continue;
for(int j = i+1; j <= n; j++) {
if(v[i]+v[j] > S)
break;
ins(v[i]+v[j]);
}
int I = i-1;
if(S-v[I] < 0)
continue;
for(int j = 1; j <= I-1; j++) {
if(S-v[I]-v[j] < 0)
break;
for(int k = 1; k <= j-1; k++) {
if(S-v[I]-v[j]-v[k] < 0)
break;
ach = S-v[I]-v[j]-v[k];
rez += get(ach);
}
}
}
out << rez << '\n';
return 0;
}
I think it can be done. We are looking for all subsets of 5 items in the array arr with the correct SUM. We have array with indexes 0..N-1. Third item of those five can have index i in range 2..N-3. We cycle through all those indexes. For every index i we generate all combinations of two numbers for index in range 0..i-1 on the left of index i and all combinations of two numbers for index in the range i+1..N-1 on the right of index i. For every index i there are less than N*N combinations on the left plus on the right side. We would store only sum for every combination, so it would not be more than 1000 * 1000 * 4 = 4MB.
Now we have two sequences of numbers (the sums) and task is this: Take one number from first sequence and one number from second sequence and get sum equal to Si = SUM - arr[i]. How many combinations are there? To do it efficiently, sequences have to be sorted. Say first is sorted ascending and have numbers a, a, a, b, c ,.... Second is sorted descending and have numbers Z, Z, Y, X, W, .... If a + Z > Si then we can throw Z away, because we do not have smaller number to match. If a + Z < Si we can throw away a, because we do not have bigger number to match. And if a + Z = Si we have 2 * 3 = 6 new combinations and get rid of both a and Z. If we get sorting for free, it is nice O(N^3) algorithm.
While sorting is not for free, it is O(N * N^2 * log(N^2)) = O(N^3 * log(N)). We need to do sorting in linear time, which is not possible. Or is it? In index i+1 we can reuse sequences from index i. There are only few new combinations for i+1 - only those that involve number arr[i] together with some number from index 0..i-1. If we sort them (and we can, because there are not N*N of them, but N at most), all we need is to merge two sorted sequences. And that can be done in linear time. We can even avoid sorting completely if we sort arr at the beginning. We just merge.
For second sequence the merging does not involve adding but removing, but it is very simmilar.
The implementation seems to work, but I expect there is off by one error somewhere ;-)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
int Generate(int arr[], int i, int sums[], int N, int NN)
{
int p1 = 0;
for (int i1 = 0; i1 < i - 1; ++i1)
{
int ai = arr[i1];
for (int i2 = i1 + 1; i2 < i; ++i2)
{
sums[p1++] = ai + arr[i2];
}
}
sort(sums, sums + p1);
return p1;
}
int Combinations(int n, int sums[], int p1, int p2, int NN)
{
int cnt = 0;
int a = 0;
int b = NN - p2;
do
{
int state = sums[a] + sums[b] - n;
if (state > 0) { ++b; }
else if (state < 0) { ++a; }
else
{
int cnta = 0;
int lastA = sums[a];
while (a < p1 && sums[a] == lastA) { a++; cnta++; }
int cntb = 0;
int lastB = sums[b];
while (b < NN && sums[b] == lastB) { b++; cntb++; }
cnt += cnta * cntb;
}
} while (b < NN && a < p1);
return cnt;
}
int Add(int arr[], int i, int sums[], int p2, int N, int NN)
{
int ii = N - 1;
int n = arr[i];
int nn = n + arr[ii--];
int ip = NN - p2;
int newP2 = p2 + N - i - 1;
for (int p = NN - newP2; p < NN; ++p)
{
if (ip < NN && (ii < i || sums[ip] > nn))
{
sums[p] = sums[ip++];
}
else
{
sums[p] = nn;
nn = n + arr[ii--];
}
}
return newP2;
}
int Remove(int arr[], int i, int sums[], int p1)
{
int ii = 0;
int n = arr[i];
int nn = n + arr[ii++];
int pp = 0;
int p = 0;
for (; p < p1 - i; ++p)
{
while (ii <= i && sums[pp] == nn)
{
++pp;
nn = n + arr[ii++];
}
sums[p] = sums[pp++];
}
return p;
}
int main() {
ifstream in("take5.in");
ofstream out("take5.out");
int N, SUM;
in >> N >> SUM;
int* arr = new int[N];
for (int i = 0; i < N; i++)
in >> arr[i];
sort(arr, arr + N);
int NN = (N - 3) * (N - 4) / 2 + 1;
int* sums = new int[NN];
int combinations = 0;
int p1 = 0;
int p2 = 1;
for (int i = N - 3; i >= 2; --i)
{
if (p1 == 0)
{
p1 = Generate(arr, i, sums, N, NN);
sums[NN - 1] = arr[N - 1] + arr[N - 2];
}
else
{
p1 = Remove(arr, i, sums, p1);
p2 = Add(arr, i + 1, sums, p2, N, NN);
}
combinations += Combinations(SUM - arr[i], sums, p1, p2, NN);
}
out << combinations << '\n';
return 0;
}
For some reason it's taken me a while to get my head around this one, but there's one bit I'm still not sure about.
In the code below, this bit:
a.at(first) = a.at(last);
a.at(last) = a.at(++first);
a.at(first) = pivot;
My question is, when a.at(++first) is swapped with a.at(last), it hasn't been compared, has it? a.at(last) is lower that the pivot, so is being moved, but there is no way of knowing if a.at(++first) is greater than or equal to pivot, is there? Or am I missing something?
#include <iostream>
#include <vector>
using namespace std;
void quick(vector<int>&);
void quick_helper(vector<int>&, int, int);
void print(vector<int>);
int main(){
vector<int>v(10);
v.at(0) = 8;
v.at(1) = 3;
v.at(2) = 7;
v.at(3) = 2;
v.at(4) = 5;
v.at(5) = 9;
v.at(6) = 1;
v.at(7) = 4;
v.at(8) = 0;
v.at(9) = 6;
cout << "Before sorting:\n";
print(v);
quick (v);
cout << "After sorting:\n";
print(v);
return 0;
}
void print(vector<int> a)
{
for (int i = 0; i < static_cast<int>(a.size()); i++)
cout << a[i] << " ";
cout << "\n";
}
void quick(vector<int>& a){
quick_helper(a, 0, static_cast<int>(a.size() - 1));
}
void quick_helper(vector<int>& a, int l, int r){
int i, first, last, pivot;
if (r>l){
first = l;
last = r;
i = (l+r)/2;
pivot = a.at(i);
a.at(i) = a.at(first);
a.at(first) = pivot;
while (last > first){
if (a.at(last) >= pivot){
last--;
} else {
a.at(first) = a.at(last);
a.at(last) = a.at(++first);
a.at(first) = pivot;
}
}
pivot = first;
quick_helper(a, l, pivot-1);
quick_helper(a, pivot+1, r);
}
return;
}
there is no way of knowing if a.at(++first) is greater than or equal to pivot
Yes you are right, a.at(++first) is just an unknown value that takes place of the swapped one. It will be compared on the next while-loop iteration in if (a.at(last) >= pivot) last--.
It works because your pivot is always at first position.
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.