I'm beginning to learn about C++. I've been putting it off for a long time and I decided to start learning it.
Currently, I'm having trouble finding the issue with my program. My program is supposed to take integers from the input, insert it into an array, and then sort it. Everything is working correctly-- even the sorting... most of the time...
Sometimes the sorting works as intended. Sometimes it spits the numbers out in random orders. Sometimes it output really weird negative and positive integers that are very close to the upper and minimum bounds that integers can go. After hours of trying to figure out something about this, I just can't figure it out. I've been thinking that it has something with the pointers for the array? But I'm unsure because I barely know how pointers work.
I've tried setting the array to hard-coded values and sorting with different algorithms, none of which helped whatsoever.
#include <iostream>
/*Sorting program*/
using namespace std;
int* sortArray(int* array, int size) {
for (int i = 0; i < size; i++) {
int lowest;
for (int k = i; k < size; k++) {
if (array[k] < array[i] && array[k] < array[lowest]) {
cout << array[k] << " is less than " << array[i] << endl;
lowest = k;
}
}
int temp = array[lowest];
array[lowest] = array[i];
array[i] = temp;
}
return array;
}
int main() {
int low, high, target, size;
cout << "Enter size of array : ";
cin >> size;
int *array = new int[size];
for (int i = 0; i < size; i++) {
cout << "Enter array[" << i << "] : " << endl;
int entry;
cin >> entry;
array[i] = entry;
}
/* */
array = sortArray(array, size);
for (int i = 0; i < size; i++) {
cout << "array[" << i << "] = " << array[i] << endl;
}
return 1;
}
Output
>>OutputFile.exe
Enter size of array : 4
Enter array[0] :
3
Enter array[1] :
4
Enter array[2] :
7
Enter array[3] :
4
array[0] = 2059292487
array[1] = 3
array[2] = 4
array[3] = 7
Output (program ran again, nothing changed)
>>OutputFile.exe
Enter size of array : 8
Enter array[0] :
3
Enter array[1] :
4
Enter array[2] :
8
Enter array[3] :
1
Enter array[4] :
88
Enter array[5] :
4
Enter array[6] :
5
Enter array[7] :
6
array[0] = 1
array[1] = 3
array[2] = 4
array[3] = 4
array[4] = 5
array[5] = 6
array[6] = 8
array[7] = 88