Here is my code below, basically it lets me input the numbers for the array but I have tried so much and still both of the functions to output both the original and sorted array will not output the arrays. I am not sure as to why exactly it will not output the arrays, I have messed around with changing values, rearranging the functions, changing the function arguments, but I just couldn't get it to output what I want it to. I am also unsure if my variables for my first two functions and last function are linking properly as that could also be the issue, but I mainly just need the program to output both the original array and the sorted array.
#include <bits/stdc .h>
#include <vector>
#include <iostream>
using namespace std;
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i ) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j 1] = arr[j];
j = j - 1;
}
arr[j 1] = key;
}
}
void printArray(int arr[], int n) {
int i;
for (i = 0; i < n; i )
std::cout << arr[i] << " ";
std::cout << endl;
}
int main(int arr[], int n) {
std::cout << "How large would you like the array to be?: ";
int sizeArray;
std::cin >> sizeArray;
std::vector < int > array;
for (int i = 0; i < sizeArray; i) {
std::cout << "Input each number for the array: \n";
int n;
std::cin >> n;
array.push_back(n);
}
for (auto n: array) {
std::cout << n << ",";
}
insertionSort( & arr[sizeArray], n);
printArray( & arr[sizeArray], n);
//(&arr[sizeArray], n)
}
CodePudding user response:
int main(int arr[], int n)
is not a valid signature for main()
, so right off the bat your code has undefined behavior. Since you don't use any command-line parameters, use int main()
instead.
Also, don't use <bits/stdc .h>.
But, regarding your code logic, when main()
is calling insertionSort()
and printArray()
, it is passing a pointer to the invalid arr
rather than the populated vector array
. But fixing that, &array[sizeArray]
would be out of bounds of the vector, it needs to be &array[0]
instead, or better array.data()
. And n
does not hold the size of the vector, you need to use sizeArray
instead, or better array.size()
.
Try this instead:
int main() {
...
insertionSort( array.data(), array.size());
printArray( array.data(), array.size());
}