Void seems not to work inside Main function

Hi, I just got back to school and I haven't program in years.
I got some basic C++ but I have been stuck with this program for a while.
I'm writing a program that supposed to read a binary file and sort it with the sorting option of Bubble sort & selection sort.
I was provided with the binaryReadFile and a Timing File.
I was not sure how to implement this .cpp code to my own main code.
Do I need to change it and make it into a class or a void function?
this is the code that I have to read the binary file.

Also, can someone explain to me what is the function of having timing.cpp, supposedly what it does: Defines the entry point for the console application. If someone can elaborate this in simpler words?
Thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  // BinaryFileRead.cpp
//
#include <iostream>

using namespace std;

int main()
{
	int* arrayToSort;
	char fileName[50];
	int size, readVal;

	cout << "Enter a filename to sort => ";
	cin >> fileName;

	FILE* inFile;

	fopen_s(&inFile, fileName, "rb");
	fread(&size, sizeof(size), 1, inFile);
	arrayToSort = new int[size];

	for (int i = 0; i < size; i++) {
		fread(&readVal, sizeof(readVal), 1, inFile);
		arrayToSort[i] = readVal;
	}

	fclose(inFile);
	return 0;
}
Last edited on
Do I need to change it and make it into a class or a void function?

do you know what a class is? do you know what a void function is?
If not, before you can decide, you need to know what the words mean.

a class is a user defined type (and the self-operations on that type).
a void function does not return a value, as opposed to a function that returns say a double.

your file reading is in C, is this supposed to be C code or C++ (we can talk either, but it helps to know). If it is c++, you should use c++ files ( <fstream> ) and not file pointers.

not sure what timing.cpp is, sounds like code you were given, and from its name I can guess that it sees low long something ran so you can compare the 2 sorts in terms of wall clock time / performance.

think before you code. you need to have a clear idea of what you want to do, how you want to do it, and the steps involved before you try to code anything.
After line 26, first just try printing each number in arrayToSort. Make sure the numbers printed match what you expect.

After you have confirmed that it is reading and printing the contents of the file correct, then you want to sort the array. Since you specifically mentioned bubble sort, I imagine your instructor doesn't want you to use qsort or std::sort, but you might want to confirm that.

There are plenty of tutorials online for how to implement bubble sort, but try it yourself first.

For example, you could make a function:
1
2
3
4
void bubbleSort(int arr[], int size)
{
    // ...
}


And you call it at some point after line 26.
bubbleSort(arrayToSort, size);
Hello luiz5z,

You wrote:
I was provided with the binaryReadFile and a Timing File.

That is great, but you are asking questions about a file, (Timing File), that no one knows about or that is in it or how to use it.

I was not sure how to implement this .cpp code to my own main code.

Again having no idea what is in the file how do you expect anyone to give you an answer.

Also, can someone explain to me what is the function of having timing.cpp, supposedly what it does

No. Because no one knows what is in the file.

The answers from jonnin and Ganado are based on what is seen not what is not seen. At the moment that is all anyone can do.

It would also help to mention what IDE you are using, if any, or how you are compiling the program.

You have been asked if this is a C or C++ program. It would help to know which way to go with answers.

Andy
it is a C++ program.

and timing.cpp have the following program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Timing.cpp : Defines the entry point for the console application.


#include <iostream>
#include <time.h> //ctime
#include <sys/timeb.h> //_timeb _ftime_s
#include "timing.h"

using namespace std;

int main()
{
	struct _timeb timebuffer;
	char timeline[26];

	_ftime_s(&timebuffer);
	ctime_s(timeline, sizeof(timeline), &(timebuffer.time));

	printf("The time is %.19s.%hu %s", timeline, timebuffer.millitm, &timeline[20]);

	system("pause");
	return 0;
}
turn that main into its own function that does the timing for the new program; it is of no use as-is.

so it does need to be its own function (or if you have need, a full class).
I was able to read the file and show the timing now.
But it seems that my program doesn't do the sorting.
Is it something wrong with my printArray?
Currently I don't know if my Sorting method is working

When I tried to declare all my global variable as a local variable, it kept giving me this error:
arr undeclared identifier.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h> //ctime
#include <sys/timeb.h> //_timeb _ftime_s


using namespace std;

//Global Variable
int* arrayToSort;
int* arr;
int size;
int i, j;
int temp;


void timing() {
	struct _timeb timebuffer;
	char timeline[26];

	_ftime_s(&timebuffer);
	ctime_s(timeline, sizeof(timeline), &(timebuffer.time));

	printf("The time is %.19s.%hu %s", timeline, timebuffer.millitm, &timeline[20]);

	system("pause");
}

void swapped(int* ap, int* bp) {
	int temp = *ap;
	*ap = *bp;
	*bp = temp;
}

//Bubble Sort
void bubbleSort(int arrayToSort[], int size)
{
	arrayToSort[i];
	int x, y;
	bool swap;
	for (x = 0; x > size - 1; x--) {
		swap = false;
		for (int y = 0; y < size - x - 1; y++) {
			if (arrayToSort[y] > arrayToSort[y + 1])
				swapped(&arrayToSort[y], &arrayToSort[x]);
			swap = true;
		}
		if (swap == false)
			break;
	}
}

//Selection Sort
void selectionSort(int arr[], int size) {
	for (i = size - 1; i > 0; i--) {
		int best = 0;//
		for (j =1+ 1; j < size; j++) {
			if (arr[best] > arr[j]) //
				best = j;
		}
		swapped(&arr[best], &arr[i]);
	}
}

//Insertion Sort?
void insertionSort(int arr[], int size) {
	for (int i = 1; 1 < size; i++) {
		temp = arr[i];//
		j = i - 1;
		while (j >= 0 && arr[j] > temp)
		{
			arr[j + 1] = arr[j];
			j = j - 1;
		}
		arr[j + 1] = temp;
	}
}

//shellsort
void shellSort(int arr[], int size)
{
	int Ns;
	int Head;
	int RE;

	for (Ns = size / 2; Ns >= 1; Ns /= 2) {
		for (Head = Ns + 1; size;) {
			arr[Head]=arr[0];//
			RE = Head - Ns;
		}
		while (RE>=0 && arr[0] < RE) {
			arr[RE]=arr[RE + Ns];
			RE = RE - Ns; //break out of loop when(-)
		}
	}
}

//displaying array after being sorted
void printArray(int arrayToSort[], int size) {

	for (i = 0; i < size; i++)
	{
		cout << arrayToSort[i] << " ";
		cout << endl;
	}
}

int main()
{
	int choice;
	int temp;
	clock_t startTime, endTime; //for calculating time
	double totalTime; //calculating total time
	int* arrayToSort;
	char fileName[50];
	int  size, readVal;

	//read data from file.bin
	cout << "Enter a filename to sort => ";
	cin >> fileName;

	FILE* inFile;

	fopen_s(&inFile, fileName, "rb");
	fread(&size, sizeof(size), 1, inFile);
	arrayToSort = new int[size];

	for (int i = 0; i < size; i++) {
		fread(&readVal, sizeof(readVal), 1, inFile);
		arrayToSort[i] = readVal;
	}

	fclose(inFile);

	//ask user which type of sorting they want to use
	cout << "Please make the following selection:" << endl;
	cout << "1. Bubble Sort:" << endl;
	cout << "2. Selection Sort: " << endl;
	cout << "3. Insertion Sort: " << endl;
	cout << "4. Shell Sort: " << endl;
	cin >> choice;

	//choice of sorting method
	switch (choice) {
	case 1: cout << "You have chosen Bubble Sort:" << endl;
		startTime = clock();
		bubbleSort(arr, size);
		printf("Sorted array: \n");
		printArray(arrayToSort, size);
		endTime = clock();
		printf("%f\n", (float)endTime);
		totalTime = ((double)(endTime - startTime));
		printf("\n\nendtime : %f\n", (float)endTime);
		printf("\n\ntotal time of execution = %f", totalTime);
		break;
	case 2: cout << "You have chosen Selection Sort:" << endl;
		startTime = clock();
		selectionSort(arr, size);
		printf("Sorted array: \n");
		endTime = clock();
		printf("%f\n", (float)endTime);
		totalTime = ((double)(endTime - startTime));
		printArray(arrayToSort, size);
		printf("\n\nendtime : %f\n", (float)endTime);
		printf("\n\ntotal time of execution = %f", totalTime);
		break;
	case 3: cout << "You have Chosen Insertion Sort:" << endl;
		startTime = clock();
		insertionSort(arr, size);
		printf("Sorted array: \n");
		endTime = clock();
		printf("%f\n", (float)endTime);
		totalTime = ((double)(endTime - startTime));
		printArray(arrayToSort, size);
		printf("\n\nendtime : %f\n", (float)endTime);
		printf("\n\ntotal time of execution = %f", totalTime);
		break;
	case 4: cout << "You have Chosen Shell Sort: " << endl;
		startTime = clock();
		shellSort(arr, size);
		printf("Sorted array: \n");
		endTime = clock();
		printf("%f\n", (float)endTime);
		totalTime = ((double)(endTime - startTime));
		printArray(arrayToSort, size);
		printf("\n\nendtime : %f\n", (float)endTime);
		printf("\n\ntotal time of execution = %f", totalTime);
	}
	return 0;
}
I had to remove the unsupported _s microsoftisms and change a couple of other little things. This compiles on my g++ now, but lacking a file, I can't test it any farther.

-globals should still be removed.
use the c++ headers if its c++: <ctime>, <cstdlib>
- shell short should use a good sequence, not a function like that. there are several to pick from but its generally understood that you stuff them into an array of constants rather than try to compute them.
maybe try <chrono> to do timers, rather than the stuff you used. This isnt critical but its a much better timing tool.
maybe try to use cout everywhere; printf has its moments (mostly, to print doubles formatted multiple ways without the bloated mess that cout needs to do that) but 99% of the time you should not be using printf at all.
I am not sure where you are learning from but this is almost half C style, or c++ 1990s style. C casts, printfs, timing tool, headers, file* (using ifstream in c++ is better usually), etc are all C code. Just be aware that the things you are doing are more C than c++ for now, but if you can find a better book or whatever, you should do so.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h> //ctime
#include <sys/timeb.h> //_timeb _ftime_s


using namespace std;

//Global Variable
int* arrayToSort;
int* arr;
int size;
int i, j;
int temp;


void timing() 
{
	 timeb timebuffer;
	//char timeline[26];
	time_t timeline;

	ftime(&timebuffer);
	ctime(&timeline);

	printf("The time is %.19s.%hu %s", timeline, timebuffer.millitm, &timeline);

	system("pause");
}

void swapped(int* ap, int* bp) {
	int temp = *ap;
	*ap = *bp;
	*bp = temp;
}

//Bubble Sort
void bubbleSort(int arrayToSort[], int size)
{
	arrayToSort[i];
	int x, y;
	bool swap;
	for (x = 0; x > size - 1; x--) {
		swap = false;
		for (int y = 0; y < size - x - 1; y++) {
			if (arrayToSort[y] > arrayToSort[y + 1])
				swapped(&arrayToSort[y], &arrayToSort[x]);
			swap = true;
		}
		if (swap == false)
			break;
	}
}

//Selection Sort
void selectionSort(int arr[], int size) {
	for (i = size - 1; i > 0; i--) {
		int best = 0;//
		for (j =1+ 1; j < size; j++) {
			if (arr[best] > arr[j]) //
				best = j;
		}
		swapped(&arr[best], &arr[i]);
	}
}

//Insertion Sort?
void insertionSort(int arr[], int size) {
	for (int i = 1; 1 < size; i++) {
		temp = arr[i];//
		j = i - 1;
		while (j >= 0 && arr[j] > temp)
		{
			arr[j + 1] = arr[j];
			j = j - 1;
		}
		arr[j + 1] = temp;
	}
}

//shellsort
void shellSort(int arr[], int size)
{
	int Ns;
	int Head;
	int RE;

	for (Ns = size / 2; Ns >= 1; Ns /= 2) {
		for (Head = Ns + 1; size;) {
			arr[Head]=arr[0];//
			RE = Head - Ns;
		}
		while (RE>=0 && arr[0] < RE) {
			arr[RE]=arr[RE + Ns];
			RE = RE - Ns; //break out of loop when(-)
		}
	}
}

//displaying array after being sorted
void printArray(int arrayToSort[], int size) {

	for (i = 0; i < size; i++)
	{
		cout << arrayToSort[i] << " ";
		cout << endl;
	}
}

int main()
{
	int choice;
	int temp;
	clock_t startTime, endTime; //for calculating time
	double totalTime; //calculating total time
	int* arrayToSort;
	char fileName[50];
	int  size, readVal;

	//read data from file.bin
	cout << "Enter a filename to sort => ";
	cin >> fileName;

	FILE* inFile;

	inFile = fopen(fileName, "rb");
	fread(&size, sizeof(size), 1, inFile);
	arrayToSort = new int[size];

	for (int i = 0; i < size; i++) {
		fread(&readVal, sizeof(readVal), 1, inFile);
		arrayToSort[i] = readVal;
	}

	fclose(inFile);

	//ask user which type of sorting they want to use
	cout << "Please make the following selection:" << endl;
	cout << "1. Bubble Sort:" << endl;
	cout << "2. Selection Sort: " << endl;
	cout << "3. Insertion Sort: " << endl;
	cout << "4. Shell Sort: " << endl;
	cin >> choice;

	//choice of sorting method
	switch (choice) {
	case 1: cout << "You have chosen Bubble Sort:" << endl;
		startTime = clock();
		bubbleSort(arr, size);
		printf("Sorted array: \n");
		printArray(arrayToSort, size);
		endTime = clock();
		printf("%f\n", (float)endTime);
		totalTime = ((double)(endTime - startTime));
		printf("\n\nendtime : %f\n", (float)endTime);
		printf("\n\ntotal time of execution = %f", totalTime);
		break;
	case 2: cout << "You have chosen Selection Sort:" << endl;
		startTime = clock();
		selectionSort(arr, size);
		printf("Sorted array: \n");
		endTime = clock();
		printf("%f\n", (float)endTime);
		totalTime = ((double)(endTime - startTime));
		printArray(arrayToSort, size);
		printf("\n\nendtime : %f\n", (float)endTime);
		printf("\n\ntotal time of execution = %f", totalTime);
		break;
	case 3: cout << "You have Chosen Insertion Sort:" << endl;
		startTime = clock();
		insertionSort(arr, size);
		printf("Sorted array: \n");
		endTime = clock();
		printf("%f\n", (float)endTime);
		totalTime = ((double)(endTime - startTime));
		printArray(arrayToSort, size);
		printf("\n\nendtime : %f\n", (float)endTime);
		printf("\n\ntotal time of execution = %f", totalTime);
		break;
	case 4: cout << "You have Chosen Shell Sort: " << endl;
		startTime = clock();
		shellSort(arr, size);
		printf("Sorted array: \n");
		endTime = clock();
		printf("%f\n", (float)endTime);
		totalTime = ((double)(endTime - startTime));
		printArray(arrayToSort, size);
		printf("\n\nendtime : %f\n", (float)endTime);
		printf("\n\ntotal time of execution = %f", totalTime);
	}
	return 0;
}
Last edited on
jonnin thank you.
I'm more familiary with C language and I only started using C++.

deleted all the global variable.

How do I swap the array that was read from the file to the arr[i] inside the Bubble sort?
it seems that I was reading the file but was not doing the sorting as it seems the value didn't pass to the Bubble Sort array.
this is my current Bubble sort.
I did some modification to the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void bubbleSort(int arr[], int size)
{
	int i;
	arr[i];
	int x, y;
	bool swap;
	for (x = 0; x > size - 1; x--) {
		swap = false;
		for (int y = 0; y < size - x - 1; y++) {
			if (arr[y] > arr[y + 1])
				swapped(arr[y], arr[x]);
			swap = true;
		}
		if (swap == false)
			break;
	}
}


1
2
3
4
5
6
void swapped(int &a, int &b) {
	int temp;
	temp = a;
	a = b;
	b = temp;
}


1
2
3
4
5
6
7
8
9
10
11
12
switch (choice) {
	case 1: cout << "You have chosen Bubble Sort:" << endl;
		startTime = clock();
		bubbleSort(arr, size);
		printf("Sorted array: \n");
		printArray(arrayToSort, size);
		endTime = clock();
		printf("%f\n", (float)endTime);
		totalTime = ((double)(endTime - startTime));
		printf("\n\nendtime : %f\n", (float)endTime);
		printf("\n\ntotal time of execution = %f", totalTime);
		break;
(1)
1
2
	int i;
	arr[i];
i is not initialized; its value should not be used. But you attempt to access the i'th element of arr. Delete the "arr[i];" line.

(2)
for (x = 0; x > size - 1;
x is initially 0, but the condition for looping is "x must be greater than size - 1", where size is presumably supposed to be a positive number. This will never loop.

You either meant:
x = 0; x < size; x++
or
x = size - 1; x >= 0; x --

(3)
1
2
3
4
5
		for (int y = 0; y < size - x - 1; y++) {
			if (arr[y] > arr[y + 1])
				swapped(arr[y], arr[x]);
			swap = true;
		}

This calls swap = true every iteration. You should put the swap = true line within the if statement.

PS:
In general, you should use declare a variable in the smallest scope that it is needed.

So instead of, for example:
1
2
3
4
5
int i;
int j;
for (i = 0; i < size; i++)
    for (j = 0; j < size; j++)
        /* ... */ ;

It is recommended to have:
1
2
3
for (int i = 0; i < size; i++)
    for (int j = 0; j < size; j++)
        /* ... */ ;

This prevents i from being used in an uninitialized context (outside of the loop).
Last edited on
@Ganado, thank you for the input!
I follow your instruction but for some reason it seems to gave me the same result.
I tried to see if it is my printArray that been giving me trouble and I tried using this:
But it seems to give me the same unsorted number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
case 1: cout << "You have chosen Bubble Sort:" << endl;
		startTime = clock();
		bubbleSort(arr, size);
		printf("Sorted array: \n");
		for (int i = 0; i < size; i++)
		{
			cout << arr[i] << " ";
			cout << endl;
		}
		endTime = clock();
		printf("%f\n", (float)endTime);
		totalTime = ((double)(endTime - startTime));
		printf("\n\nendtime : %f\n", (float)endTime);
		printf("\n\ntotal time of execution = %f", totalTime);
		break;
maybe try <chrono> to do timers


I found chrono confusing when I started using it. A possible timing using chrono could be:

1
2
3
4
5
6
7
8
9
#include <chrono>
...

const auto starttim = std::chrono::high_resolution_clock::now();

// code to time goes here

const auto difftim = std::chrono::high_resolution_clock::now() - starttim;
std::cout << "Time used was " << std::chrono::duration<double, std::milli>(difftim).count() << " ms" << std::endl;

But it seems to give me the same unsorted number


This is where the debugger becomes your new best friend. Use it to trace through the code and show variable values. You'll then find where the code deviates from what is expected and hence where is the problem. All programmers need to become familiar with using the debugger.
For bubble sort, this can be 'simplified'. Consider:

1
2
3
4
5
6
7
8
9
10
11
12
void bubbleSort(int a[], int n)
{
	do {
		int newn = 1;

		for (int i = 1; i < n; ++i)
			if (a[i - 1] > a[i])
				std::swap(a[i - 1], a[newn = i]);

		n = newn;
	} while (n > 1);
}


Note std::swap() is a C++ function to swap the two arguments. You'll need to have #include <algorithm> at the top of the program to use.
Thank you @seeplus!

My program is working on all sorted method. Now I need to have the user choose the range of sorted array to be printed.

So after picking a sort the user should see the start time, then a pause while the sort happens, then the end time should print, then they should be prompted for the lower and upper bounds, then that range of numbers should be printed out.

I was thinking that it should be implamented in the void printArray?

Also I'm not quite sure why my instructor asked for a pause while the sort happened as the whole deal of having a time is to see how long it took.
I moved the timing to the main code so it looks something like this:

1
2
3
4
5
//timing
	_ftime_s(&timebuffer);
	ctime_s(timeline, sizeof(timeline), &(timebuffer.time));
	printf("The time is %.19s.%hu %s", timeline, timebuffer.millitm, &timeline[20]);
	system("pause");


place it before the switch, so the switch look something like this:
1
2
3
4
5
6
7
case 1: cout << "You have chosen Bubble Sort:" << endl;
		bubbleSort(arr, size);
		printf("\nPlease wait while array being sorted.....\n");
		printf("The start time is %.19s.%hu %s", timeline, timebuffer.millitm, &timeline[20]);
		printf("Sorted array: \n");
		printArray(arr, size);
		break;


I was able to sort 1000000 unsorted binary number but for somereason it always stop printing around 364800.
drop the latest code in; too many changes since last full copy to try to spot a bug.
also make sure its not something silly like trying to print a million in the console ... and running out of buffer space, so some of the values 'scroll off' the screen... you can redirect a program to a text file if you want to with
c:\> program.exe > filename (works in unix too, > filename part that is)
its also infinitely faster to dump to a file than the console.


Also I'm not quite sure why my instructor asked for a pause while the sort happened as the whole deal of having a time is to see how long it took.


They're not. Read what you wrote again carefully.

user should see the start time, then a pause while the sort happens, then the end time


From the users perspective, the user will see the start time displayed, then the user will see a pause in the display whllst the numbers are sorted and then will see the end time displayed. The instructor is not asking you to insert a pause.
Last edited on
Topic archived. No new replies allowed.