This program is designed to give out randomized numbers depending on how many the user, inputs as the size of array. The rand()
is working and gives outputs elements depending on the user. The problem is when it comes to the part where it is getting sorted the elements of the array seems to be changing from a different value.
#include <iostream>
#include <ctime>
using namespace std;
int SizeArray = 0;
int setArray[] = { NULL };
int tempA, half;
int main() {
cout << "Enter number of elements: ";
cin >> SizeArray;
srand(time(0));
for (int i = 0; i < SizeArray; i++) {
setArray[i] = 51 + rand() % (100 - 51);
}
cout << "\n\n\nraw input " << endl;
for (int i = 0; i < SizeArray; i++) {
cout << setArray[i] << "\t";
}
half = SizeArray / 2;
cout << "\n\n\nfirst half " << endl;
for (int j = 0; j < half; j++){
for (int i = 0; i < half; i++){
if (setArray[i] > setArray[i + 1]){
tempA = setArray[i];
setArray[i] = setArray[i + 1];
setArray[i + 1] = tempA;
}
}
}
for (int i = 0; i < half; i++){ //to print the sorted array
cout << setArray[i] << "\t";
}
cout << "\n\n\nsecond half " << endl;
for (int i = half; i < SizeArray; i++){ //to print the second half
cout << setArray[i] << "\t";
}
cout << "\n\n\nmerge " << endl;
for (int i = 0; i < SizeArray; i++) { //to print all elements of the array
cout << setArray[i] << "\t";
}
}
example of error there should be no "4" there
I'm hoping to know why the elements are changing and what are some possible solution to it. If you did answer, thank you in advance, I would reply if you got any question in my codes.
Aucun commentaire:
Enregistrer un commentaire