I am attempting to use bubble sort in C++ which I am new to. This is my code so far:
My issue is that when ever I try and sort the arrays, the integer array is set to zero at every index.
Could this have something to do with memory allocation?
#include <iostream>
#include <cstring>
#include <array>
using namespace std;
int main() {
//requires users input to create an array that wouldn't use too much memory
cout << "Enter number of dealers you wish to enter" << endl;
int array_size;
cin >> array_size;
std::string sales_names[array_size]; //makes a 2D array that can have 15 rows and 2 colums {Name, sales total}
int sales_data[array_size];
for(int i = 0; i < array_size; i++){
std::string dealers_name;
int dealers_value;
cout << "Enter Dealers Name: ";
cin >> dealers_name;
cin.clear();
cout << "Enter Dealers Sales: ";
cin >> dealers_value;
sales_names[i] = dealers_name;
sales_data[i] = dealers_value;
cout << endl;
}
string temp_name;
int temp_value;
//Bubble Sort?
for(int i = 0; i < array_size; i++){
for(int k = 0; k < array_size; k++){
if(sales_data[k] = sales_data[k+1])
{
temp_value = sales_data[k];
temp_name = sales_names[k];
sales_data[k] = sales_data[k+1];
sales_names[k] = sales_names[k+1];
sales_data[k+1] = temp_value;
sales_names[k+1] = temp_name;
}
}
}
for(int i = 0; i < array_size; i++){
cout << sales_data[i] << endl;
cout << sales_names[i] << endl;
}
return 0;
}
Im not sure why, but after the first loop of the for loop, every item in the sales_data array is set to 0
Here is my output:
Enter number of dealers you wish to enter
3
Enter Dealers Name:test1
Enter Dealers Sales:12
Enter Dealers Name:test2
Enter Dealers Sales:6
Enter Dealers Name:test3
Enter Dealers Sales:9
0
test3
0
test2
0
test1
Thanks in advance
Your comparison is wrong:
if (sales_data[k] = sales_data[k + 1])
This should be a <
(or a >
, depending on if you want to sort ascending or descending). Even if you wanted to test for equality, ==
would have been right, not =
. Also here
for (int k = 0; k < array_size-1; k++) {
You should put array_size-1
, otherwise it's going out of bounds.
Also note that VLAs aren't actually part of standard C++. Use std::vector
instead:
std::vector<std::string> sales_names(array_size);
std::vector<int> sales_data(array_size);
By the way, that comment about it making a 2D array is wrong.