I'm trying to arrange a random array. In the code it's just the first step of swapping places by size. When running the code a get Debug Error and the output after the swap shows that the first number in the array was deleted and the last is a long random number that was in the memory. It looks like it starts the swapping from i=1, why?
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void buildArray(int arr[], int size) {
srand ( (unsigned int)time(NULL) );
for(int i = 0; i < size; ++i)
arr[i] = rand() % 50 + 0;
}
void dispArray(int arr[], int size) {
for(int i = 0; i < size; ++i)
cout << i << ": " << arr[i] << endl;
}
int main()
{
const int size = 5;
int arr[size];
buildArray(arr, size);
dispArray(arr, size);
int swapHolder = -1;
for(int i = 0; i < size; ++i) {
if(arr[i] > arr[i+1]) {
swapHolder = arr[i+1];
arr[i+1] = arr[i];
arr[i] = swapHolder;
cout << endl;
}
}
dispArray(arr, size);
return 0;
}
Output example:
0: 46
1: 15
2: 47
3: 5
4: 19
0: 15
1: 46
2: 5
3: 19
4: -858993460