I'm having an issue sorting an array of 1000 integers with the following code. It worked fine with 10 integers but with 1000 it seems keep going I'm assuming it's some kind of memory leak.
I've never sorted before a small explanation of my errors would be helpful also.
Thank you
class RandomNumbers
{
private:
int intRandomNumbers;
public:
int getRandomNumbers();
void setRandomNumbers(int intPRandomNumbers);
RandomNumbers(void);
};
-----------------------------------------------------------
void printArray(const int intArray[], int intLength);
int searchFull(const int intArray[], int intLength, int intSearchItem);
void sortBubble(int intArray[], int intLength);
int searchLinear(const int intArray[], int intLength, int intSearchItem);
int searchBinary(const int intArray[], int intLength, int intSearchItem);
--------
//Getters and setters for RandomNumber class.
RandomNumbers::RandomNumbers()
{
setRandomNumbers(0);
}
void RandomNumbers::setRandomNumbers(int intPRandomNumbers)
{
intRandomNumbers = intPRandomNumbers;
}
int RandomNumbers::getRandomNumbers()
{
return intRandomNumbers;
}
void printArray(const int intArray[], int intLength) {
for(int intIndex = 0; intIndex < intLength - 1; intIndex++) {
cout << intArray[intIndex] << ", ";
}
cout << intArray[intLength - 1] << endl;
}
int searchFull(const int intArray[], int intLength, int intSearchItem) {
int intLocation = -1;
int intCounter = 1;
for(int intIndex = 0; intIndex < intLength; intIndex++) {
cerr << "searchFull: " << intCounter++ << endl;
if(intArray[intIndex] == intSearchItem)
{
intLocation = intIndex;
}
}
return intLocation;
}
void sortBubble(int intArray[], int intLength){
int intTemp = 0;
int intIteration = 0;
int intIndex = 0;
for(intIteration = 1; intIteration < intLength; intIteration++) {
for(intIndex = 0; intIndex < intLength - intIteration; intIndex++) {
if(intArray[intIndex] > intArray[intIndex + 1]) {
intTemp = intArray[intIndex];
intArray[intIndex] = intArray[intIndex + 1];
intArray[intIndex + 1] = intTemp;
}
printArray(intArray,intLength);
}
}
}
int searchLinear(const int intArray[], int intLength, int intSearchItem) {
int intLocation = -1;
int intCounter = 1;
for(int intIndex = 0; intIndex < intLength && intSearchItem >= intArray[intIndex]; intIndex++) intIndex++)
{
cerr << "searchLinear: " << intCounter++ << endl;
if(intArray[intIndex] == intSearchItem)
{
intLocation = intIndex;
}
}
return intLocation;
}
int searchBinary(const int intArray[], int intLength, int intSearchItem) {
int intFirstIndex = 0;
int intLastIndex = intLength - 1;
int intMiddle = 0;
bool boolFound = false;
while(intFirstIndex <= intLastIndex && !boolFound) {
intMiddle = (intFirstIndex + intLastIndex) / 2;
if(intArray[intMiddle] == intSearchItem) {
boolFound = true;
} else if(intArray[intMiddle] > intSearchItem) {
intLastIndex = intMiddle - 1;
} else {
intFirstIndex = intMiddle + 1;
}
cerr << "searchBinary: " << intFirstIndex << ", " << intMiddle << ", " << intLastIndex << endl;
}
if(boolFound) {
return intMiddle;
} else {
return -1;
}
}
int main() {
srand (time(NULL));
ofstream myfile;
myfile.open ("RandomNumber.txt");
if (myfile.is_open())
{
for (int i = 0; i < 1000; ++i)
{
int RandomNumbers = rand() % 1000 + 1;
myfile << RandomNumbers << "\n";
}
}
myfile.close();
int array_size = 1000;
int * array = new int[array_size];
int position = 0;
ifstream fin("RandomNumber.txt");
if(fin.is_open())
{
cout << "File opened!!! Loading array. ";
while(!fin.eof() && position < array_size)
{
fin >> array[position];
position++;
}
cout << "Displaying array..." << endl <<endl;
for(int intIndex = 0; intIndex < array_size; intIndex++)
{
cout << array[intIndex] << endl;
}
fin.close();
}
else
{
cout<< "File could not be opened." << endl;
}
cout << searchFull(array, array_size, 43) << endl;
cout << searchLinear(array, array_size, 43) << endl; //Incorrect not sorted
cout << searchFull(array, array_size, 5) << endl;
cout << searchLinear(array, array_size, 5) << endl; //Incorrect not sorted
sortBubble(array, array_size);
cout << searchFull(array, array_size, 43) << endl;
cout << searchLinear(array, array_size, 43) << endl;
cout << searchBinary(array, array_size, 43) << endl;
cout << searchFull(array, array_size, 5) << endl;
cout << searchLinear(array, array_size, 5) << endl;
cout << searchBinary(array, array_size, 5) << endl;
system("PAUSE");
return 0;
};
while(!fin.eof() is a blunder. What happens after the last value has been read, but before eof() occurs? (answer: You'll get the last entry copied twice). Fix it by going:
while ( position < array_size && fin >> array[position] )
position++;
Also, you should be displaying and sorting with position as the counter, not array_size.
Maybe your sortBubble function has a bug, or maybe it is just taking a long time to run. What happens if you try with 100 numbers? Can you post the code for it?
Related
I am working on a project for school that tests Binary Search vs. Linear Search. My LinearSearch method seems to work fine when the array is in either increasing order or reversed. However, the BinarySearch only works when the array is in increasing order, but fails to work when the array is reversed. I am not sure what is causing this and would appreciate any suggestions/solutions.
Here is my code
/*
* SearchTest.cpp
*
* Created on: Oct 16, 2022
* Author: JH
*/
#include <iostream>
#include <time.h>
using namespace std;
//BinarySearch method
int BinarySearch(int numbers[], int numbersSize, int key) {
int mid;
int low;
int high;
low = 0;
high = numbersSize - 1;
while (high >= low) {
mid = (high + low) / 2;
if (numbers[mid] < key) {
low = mid + 1;
}
else if (numbers[mid] > key) {
high = mid - 1;
}
else {
return mid;
}
}
return -1; // not found
}
//LinearSearch method
int LinearSearch(int* array, int arraySize, int key) {
for (int i = 0; i < arraySize; i++) {
if (array[i] == key) {
return i;
}
}
return -1; // not found
}
//method to reverse array elements
void reverseArray(int arr[], int start, int end)
{
while (start < end)
{
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
int main() {
//declare array
int reverseArr[1000];
int size = sizeof(reverseArr)/sizeof(reverseArr[0]);
//initialize array
for (int i = 0; i < size; i++) {
reverseArr[i] = i;
}
//reverse array
reverseArray(reverseArr, 0, size-1);
//print array
for (int i = 0; i < size; i++) {
cout << reverseArr[i] << " ";
}
cout << endl;
cout << endl;
//generate random number
srand(time(NULL));
int randomNum = rand() % 1000;
//print statements
cout << "[Linear vs. Binary Search]" << endl;
cout << "The target value is " << reverseArr[randomNum] << endl;
cout << endl;
//call BinarySearch method for array
cout << "Binary Search Test: " << endl;
int key1 = reverseArr[randomNum];
int keyIndex1 = BinarySearch(reverseArr, size, key1);
if (keyIndex1 == -1) {
cout << key1 << " was not found." << endl;
}
else {
cout << "Found " << key1 << " at index " << keyIndex1 << "." << endl;
}
cout << endl;
//call LinearSearch method for array
cout << "Linear Search Test: " << endl;
int key2 = reverseArr[randomNum];
int keyIndex2 = LinearSearch(reverseArr, size, key2);
if (keyIndex2 == -1) {
cout << key2 << " was not found." << endl;
}
else {
cout << "Found " << key2 << " at index ";
cout << keyIndex2 << "." << endl;
}
}
I want to make a c++ program that runs two algorithms - insertion and heap sort. But I keep getting an error that array size must have integral or enumeration type, not double. Where are my mistakes? I'm reading data from file.
#include "stdafx.h"
#include <stdio.h>
#include <tchar.h>
#include <random>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <time.h>
void generuoti(int _N, const char *_file);
void nuskaityti(const char *_file);
void sortInsertion(double A[], int N);
void heapSort(double A[], int N);
void heapify(double A[], int N, int i);
using namespace std;
double *Data;
double* A;
double* B;
double* A1;
double* B1;
double N;
unsigned long int palyginimai1 = 0;
unsigned long int priskyrimai1 = 0;
unsigned long int palyginimai2 = 0;
unsigned long int priskyrimai2 = 0;
int main()
{
srand(time(NULL));
cout << "generuojame atsitktinius duomenis ..." << endl;
generuoti(106000, "duom.txt");
cout << "nuskaitome duomenis ..." << endl;
nuskaityti("duom.txt");
A = new double[N];
B = new double[N];
A1 = new double[N];
B1 = new double[N];
for (int i = 0; i < N; i++) {
A[i] = Data[i];
}
//cout << "Heap array:" << endl;
for (int i = 0; i < N; i++)
//cout << A[i] << " ";
//cout << endl;
//cout << "Insertion array: " << endl;
for (int i = 0; i < N; i++)
{
B[i] = A[i];
//cout << B[i] << " ";
}
for (int i = 0; i < N; i++)
{
A1[i] = A[i];
B1[i] = B[i];
}
//cout << endl;
int nUntil = 2000;
while (nUntil <= 106000)
{
sortInsertion(B1, nUntil);
heapSort(A1, nUntil);
cout << priskyrimai1 << endl;
nUntil = nUntil * 2;
for (int i = 0; i < N; i++)
{
A1[i] = A[i];
B1[i] = B[i];
}
//cout << nUntil << palyginimai2 << " " << priskyrimai2 << endl;
}
/*cout << "Surusiuota skaiciu seka Heap:" << endl;
for (int i = 0; i < N; i++)
cout << A1[i] << " ";
cout << endl;
cout << "Surusiuota skaiciu seka Insertion:" << endl;
for (int i = 0; i < N; i++)
cout << B1[i] << " ";
cout << endl;*/
system("pause");
return 0;
}
void generuoti(int _N, const char *_file) {
ofstream os(_file);
os << _N << endl;
for (int i = 0; i < _N; i++)
{
os << " " << (double)(rand() % 1001) / (double)1000;
}
//os << " " << (double)13 << " " << (double)18 << " " << (double)25 << " " << (double)2 << " " << (double)6 << " " << (double)11 << " " << (double)16 << " " << (double)1 << " " << (double)6 << " " << (double)21 << " " << (double)17;
os.close();
}
void nuskaityti(const char *_file) {
ifstream is(_file);
if (is.fail()) {
cout << "failo nera" << endl;
exit(1);
}
is >> N;
Data = new double[N];
for (int i = 0; i < N; i++) {
is >> Data[i];
}
}
void sortInsertion(double A[], int N) {
double temp;
int hole;
for (int i = 1; i < N; i++)
{
palyginimai1++;
temp = A[i];
hole = i;
while (hole > 0 && A[hole - 1] > temp)
{
palyginimai1++;
A[hole] = A[hole - 1];
priskyrimai1++;
hole--;
}
priskyrimai1++;
A[hole] = temp;
}
}
void heapify(double A[], int N, int i)
{
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
priskyrimai2 = priskyrimai2 + 3;
if (l < N && A[l] > A[largest])
{
largest = l;
priskyrimai2++;
}
if (r < N && A[r] > A[largest])
{
largest = r;
priskyrimai2++;
}
if (largest != i)
{
swap(A[i], A[largest]);
heapify(A, N, largest);
palyginimai2++;
priskyrimai2++;
}
}
void heapSort(double A[], int N)
{
for (int i = N / 2 - 1; i >= 0; i--)
{
heapify(A, N, i);
palyginimai2++;
}
for (int i = N - 1; i >= 0; i--)
{
swap(A[0], A[i]);
priskyrimai2++;
heapify(A, i, 0);
palyginimai2++;
}
}
Also, I'm counting palyginimai - comparisons, priskyrimai-assignments.
A quick solution would be to replace anywhere you use the subscript([]) operator do this instead: A = new double[(int)N];
I hope this helps.
Count all the records from the file "8.dat". To read each individual recording perform dynamic memory capture.
Sort the records to different keys:
Item number (ascending);
The cost (descending);
Number of stock (descending).
Use selection sort
Total sorting will be done 12 times, each time the array is sorted in its original condition.
For each case count of comparisons to and permutations.
Below code implements insertion sort. Twice, without saying so much.
I need to use selection sort. How to do selection sort?
#include <iostream>
#include <fstream>
#include <conio.h>
using namespace std;
struct PRICE
{
int number;
char name[20];
int cost;
int quantity;
} *pm;
int Menu();
void PrintPRICE(PRICE);
void sort_cost(PRICE*, int);
void sort_quantity(PRICE*, int);
long file_size(const char*);
int main()
{
int count = 0;
const char *fname = "D:\8.dat";
FILE* file = fopen(fname, "r");
if (file != NULL)
{
long size = file_size(fname);
count = size / sizeof PRICE;
pm = new PRICE[count];
fread(pm, sizeof PRICE, count, file);
fclose(file);
}
for (int i=0; i<count; i++)
{
PrintPRICE(pm[i]);
cout << endl;
}
int ch = Menu();
switch (ch)
{
case 1:
{
sort_cost(pm, count);
cout << endl;
cout << " Result: " << endl;
cout << "-----------------------" << endl;
for (int i=0; i<count; i++)
{
PrintPRICE(pm[i]);
cout << endl;
}
break;
}
case 2:
{
sort_quantity(pm, count);
cout << " Result: " << endl;
cout << "-----------------------" << endl;
for (int i=0; i<count; i++)
{
PrintPRICE(pm[i]);
cout << endl;
}
break;
}
default: break;
}
delete [] pm;
_getch();
}
void PrintPRICE(PRICE price)
{
cout << " Product: " << price.name << endl;
cout << " Number of orden: " << price.number << endl;
cout << " Product cost: " << price.cost << endl;
cout << " Quantity in stock: " << price.quantity << endl;
cout << "-----------------------------------n" << endl;
}
long file_size(const char* filename)
{
FILE *Pfile = NULL;
Pfile = fopen(filename, "rb");
fseek(Pfile, 0, SEEK_END);
long size = ftell(Pfile);
fclose(Pfile);
return size;
}
void sort_cost(PRICE* array, int count)
{
int change = 0;
int comparesion = 0;
for (int i=1; i<count; i++)
{
PRICE key = array[i];
int j = i - 1;
comparesion++;
while (i>=0 && array[i].cost>key.cost)
{
array[j + 1] = array[j];
j = j - 1;
change++;
}
array[j + 1] = key;
}
cout << "n Quantity change: " << change << endl;
cout << " Quantity comparesion: " << comparesion << endl;
}
void sort_quantity(PRICE* array, int count)
{
int change = 0;
int comparesion = 0;
for (int i=1; i<count; i++)
{
PRICE key = array[i];
int j = i - 1;
comparesion++;
while (j>=0 && array[i].quantity>key.quantity)
{
array[j + 1] = array[j];
j = j - 1;
change++;
}
array[j + 1] = array[j];
}
cout << "n Quantity change: " << change << endl;
cout << " Quantity comparesion: " << comparesion << endl;
}
int Menu()
{
int n;
cout << " 1 - Sort by cost" << endl;
cout << " 2 - Sort by quantity" << endl;
cout << "n Your choice: "; cin >> n;
return n;
}
source code for the selection sort
void selectSort(int arr[], int n)
{
int pos_min,temp;
for (int i=0; i < n-1; i++)
{
pos_min = i;
for (int j=i+1; j < n; j++)
{
if (arr[j] < arr[pos_min])
pos_min=j;
}
if (pos_min != i)
{
temp = arr[i];
arr[i] = arr[pos_min];
arr[pos_min] = temp;
}
}
}
I guess that my problem is very trivial, but unfortunately (maybe because I'm really tired) I can't find a solution by myself. Well, my program generates results that I would like to write to successive lines of a text file, because I need to create a graph from them. Unfortunately, in my case, each result is saved in the same line by removing the previous result. Can you help me to improve this code? Thank you.
#include <iostream>
#include <cstring>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <fstream>
using namespace std;
int fp(int x, int y)
{
return (x<=y);
}
void sort_shell(int *tablica, int ilosc)
{
int licznik=0;
int h;
int i;
int temp;
int c=1;
fstream plik;
for (h=1; h<=ilosc/9; h=ilosc/pow(2,h));
c++;
for(; h>0; h /= 3)
{
for (i=h; i<ilosc; i++)
{
int j;
temp = tablica[i];
for (j = i-h ; j>=0; j -=h)
{
if (temp <=tablica[j])
{
tablica[j+h] = tablica[j];
licznik++;
}
else
break;
}
tablica[j+h] = temp;
}
}
/*cout << "\nPo sortowaniu Shellem." << endl;
for(i=0; i<ilosc; i++)
{
cout << tablica[i] << "\t";
}*/
plik.open( "shell.txt", std::ios::in | std::ios::out );
if(plik.good() == true)
{
plik << licznik << "\n";
plik.close();
}
//cout << "\nIlosc operacji :" << licznik << "\n";
}
void sort_hibbard(int x[], int n)
{
int i, j,k, increment, temp,licznik=0;
long swp=0, comp=0;
int val;
fstream plik;
val=log(n+1)/log(2);
increment =pow(2,val)-1;
while (increment > 0)
{
for (i=0; i<increment; i++)
{
for(j=0; j<n; j+=increment)
{
temp=x[j];
for(k=j-increment; k>=0&&temp<x[k]; k-=increment)
{
comp++;
swp++;
x[k+increment]=x[k];
licznik++;
}
x[k+increment]=temp;
swp++;
licznik++;
}
}
comp++;
val--;
if(increment!=1)
increment=pow(2,val)-1;
else
increment = 0;
}
/*cout << "\nPo sortowaniu Hibbardem." << endl;
for(i=0; i<n; i++)
{
cout << x[i] << "\t";
}*/
plik.open( "hibbard.txt", std::ios::in | std::ios::out );
if(plik.good() == true)
{
plik << licznik << "\n";
plik.close();
}
//cout << "\nIlosc operacji :" << licznik << "\n";
}
void sort_sedgewick(int *tablica, int ilosc)
{
int h = 0, i, g, t, j;
int c = 1;
int licznik = 0;
int temp;
fstream plik;
vector <int> tmp;
tmp.push_back(h);
do
{
h = (pow(4,c) + (3 * pow(2,c-1)) + 1); // funkcja z wikipedi O(N^4/3)
tmp.push_back(h);
if(h < ilosc) c++;
}while(h < ilosc);
for(g=ilosc/c;g>0;g/=c)
{
for(i=ilosc-g-1;i>=0;i--)
{
t = tablica[i];
for(j=i+g;(j<ilosc)&&!fp(t,tablica[j]);j+=g)
{
tablica[j-g] = tablica[j];
licznik++;
}
tablica[j-g] = t;
licznik++;
}
}
/*cout << "\nPo sortowaniu SEDGEWICKiem." << endl;
for(i=0;i<ilosc;i++)
{
cout << tablica[i] << "\t";
}*/
plik.open( "sedgewick.txt", std::ios::in | std::ios::out );
if(plik.good() == true)
{
plik << licznik << "\n";
plik.close();
}
//cout << "\nIlosc operacji :" << licznik << "\n";
}
int main()
{
int i, n;
//cout << "Podaj rozmiar tablicy (W tablicy znajda sie liczby od 1 do 100): ";
//cin >> n;
for(n=1000;n<=100000;n+=1000)
{
cout << n << "\n";
int zbior[n];
int prawy = 200;
srand(time(NULL));
//cout << "Przed sortowaniem." << endl;
for (int i = 0; i < n; i++)
{
if (i%2 == 0)
{
zbior[i] = rand()%prawy;
//cout << zbior[i] << "\t";
}
else
{
zbior[i] = rand()%prawy+200;
//cout << zbior[i] << "\t";
}
}
cout << endl;
sort_shell(zbior, n);
sort_hibbard(zbior, n);
sort_sedgewick(zbior, n);
}
return 0;
}
You need to use std::ios::app to append data to a file. You should also keep these files open for the duration of the reporting; you seem to be re-opening them for each iteration.
I have searched many examples and have yet to be able to find where exactly my problem lies. I am trying to implement the merge sort algorithm from the Cormen intro to algorithms book-- here is where I am at so far-- I have tried throwing in print statements to follow how the arrays are getting rebuilt but I am not seeing it... can anyone help?
Code:
#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdlib>
using namespace std;
int p = 0;
int q = 0;
int r = 0;
int getRandom()
{
int randNum = 0;
randNum = 1 + rand() % 100;
return randNum;
}
void populateArray(int * array, int size)
{
for (int i = 0; i < size; i++) {
array[i]=getRandom();
}
}
void merge (int * array, int p, int q, int r) // p = start, q = mid, r = end
{
int i = 0; // left array iterator
int j = 0; // right array iterator
int n1 = q - p + 1;
int n2 = r - q;
// int arrayL[n1 + 1];
//int arrayR[n2 + 1];
int arrayL[n1];
int arrayR[n2];
for (i = 0; i < n1; i++) {
arrayL[i] = array[p + i];
}
cout << "TEST ARRAY MS A: ";
for (int count = 0; count < n1; count++) {
cout << arrayL[count] << " ";
}
cout << endl << endl;
for (j = 0; j < n2; j++) {
arrayR[j] = array[q + j + 1];
}
cout << "TEST ARRAY MS B: ";
for (int count = 0; count < n2; count++) {
cout << arrayR[count] << " ";
}
cout << endl << endl;
//arrayL[n1 + 1] = 1000;
//arrayR[n2 + 1] = 1000;
//i = 0;
//j = 0;
for (int k = p, i = j = 0; k <= r; k++) {
if (j >= n2 || (i <= n1 && arrayL[i] <= arrayR[j])) {
array[k] = arrayL[i];
i++;
cout << "TEST ARRAY in loop A: ";
for (int tempIt = 0; tempIt < r; tempIt++) {
cout << array[tempIt] << " ";
}
cout << endl << endl;
}
else {
array[k] = arrayR[j];
j++;
cout << "TEST ARRAY in loop B: ";
for (int tempIt = 0; tempIt < r; tempIt++) {
cout << array[tempIt] << " ";
}
cout << endl << endl;
}
cout << "TEST ARRAY in loop: ";
for (int tempIt = 0; tempIt < r; tempIt++) {
cout << array[tempIt] << " ";
}
cout << endl << endl;
}
}
void mergeSort (int * array, int p, int r)
{
if (p < r) {
q = floor((p + r) / 2);
mergeSort(array, p, q);
mergeSort(array, q + 1, r);
merge(array, p, q, r);
}
}
int main(int argc, const char * argv[])
{
unsigned seed = time(0);
srand(seed);
int testArray[5];
populateArray(testArray, 5);
cout << "TEST ARRAY: ";
for (int count = 0; count < 5; count++) {
cout << testArray[count] << " ";
}
cout << endl << endl;
mergeSort(testArray, 0, 4);
cout << "TEST ARRAY after mergeSort: ";
for (int count = 0; count < 5; count++) {
cout << testArray[count] << " ";
}
cout << endl << endl;
return 0;
}