Reputation: 63
I'm new to C++ and I've been doing bubbleSort, but when I want to show the numbers in the terminal, the leading number is a problem. Sorry for my bad english btw.
where am i doing wrong?
this is the code:
#include <iostream>
void printArray(int *myArr, int lenght) {
for (int i = 0; i < lenght; ++i) {
std::cout << myArr[i] << ", ";
}
}
int bubbleSort(int *myArr, int lenght) {
for (int i = 0; i < lenght; ++i) {
for (int j = 0; j < lenght-1; ++j) {
if (myArr[j] > myArr[j+1]) {
int temp = myArr[j];
myArr[j] = myArr[j+1];
myArr[j+1] = temp;
}
}
}
return *myArr;
}
int main() {
int myArr[] = {10,14,13,19,15,12,16,18,17,11};
int newArr = bubbleSort(myArr, 8);
printArray(&newArr, 8);
return 0;
}
this is what i get:
10, 10, 12, 13, 14, 15, 16, 18,
there is no 19 and double 10s
and is there any eaiser way to get lenght of array in function? Thank you...
Upvotes: 0
Views: 80
Reputation: 81
Problem is - Wrong array size (i.e. 8) is passed to bubble sort function which produces wrong answer.
Use std::vector sothat superfluous length agrument can be avoided.
void bubbleSort(std::vector<int> & vec) {
for (int i = 0; i < vec.size(); ++i) {
...
}
}
bubbleSort(vec);
Upvotes: 0
Reputation: 48
This is the idea that should work:
#include <iostream>
#include <vector>
using namespace std;
void printArray(vector<int> arr) {
for (auto & item : arr)
{
cout << item<<' ';
}
}
void bubbleSort(vector<int> &arr)
{
bool swapp = true;
while (swapp) {
swapp = false;
for (size_t i = 0; i < arr.size() - 1; i++) {
if (arr[i] > arr[i + 1]) {
arr[i] += arr[i + 1];
arr[i + 1] = arr[i] - arr[i + 1];
arr[i] -= arr[i + 1];
swapp = true;
}
}
}
}
void main() {
vector<int> arr = { 10,14,13,19,15,12,16,18,17,11 };
bubbleSort(arr);
printArray(arr);
}
Upvotes: 1
Reputation: 122994
The problem is that you are confusing pointers with arrays with single integers.
int bubbleSort(int *myArr, int lenght) {
// ... not actually that important what happens here ...
return *myArr;
}
Your bubbleSort
gets a pointer to first element of an array passed, you do some sorting and eventually you return the first element of that sorted array (return type is int
!). This is wrong, or maybe not wrong but doesn't make much sense but the real drama will only come later...
...when here
int newArr = bubbleSort(myArr, 8);
printArray(&newArr, 8);
you copy that single integer returned from bubbleSort
into newArr
(an int
), then take its address (still "ok") and then in printArray
act like it points to an array which it doesn't (now it goes BooooM!).
myArr[i]
in printArray
is undefined behavior when i > 0
, because myArr
points to a single integer. It does not point to an array.
TL;DR: Do not use c-arrays. c-arrays are advanced C++, they are easy to get wrong and hard to get right. Use std::vector
for dynamically sized arrays and std::array
for compiletime sized arrays.
Upvotes: 3