I have problem with sorting an array. I don't know why my codes does not sort an array properly. I am new in programming so be gentle on me. Here's a code. Also other functions like merge or quick sort does not work too. Thanks in advance for answer.
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <iterator>
std::vector<int> bubbleSort(std::vector<int>& Array)
{
for (unsigned int j = 1; j < Array.size() - 1; ++j)
{
for (unsigned int i = 0; i < Array.size() - 1; i++)
{
if (Array[i] > Array[++i])
{
std::swap(Array[i], Array[++i]);
}
}
}
return Array;
}
int main()
{
for (int i = 0; i < 10;i++)
{
int N; //array size
srand(std::time(NULL));
std::cout << " array size: ";
std::cin >> N;
std::vector <int> Array;
//fill array
for (int i = 1; i <= N; i++)
Array.push_back(i);
for (int i = N - 1; i > 0; i--)
{
int j = rand() % i;
std::swap(Array[i], Array[j]);
}
bubbleSort(Array);
for (unsigned int i = 0; i < Array.size(); i++)
{
std::cout << Array.at(i) << std::endl;
}
}
system("pause");
}
It looks like you're unintentionally incrementing i within the loop. Don't use ++i, use i+1 instead. Also change your loop termination condition to just i < Array.size() instead of i < Array.size() - 1
Related
I'm trying to store random numbers in vector, but I want each number to be unique. Can I do that with for loop without using unique() or random_shuffle() ?
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL));
vector<int> v;
for (unsigned int i = 0; i < 30; i++) {
v.push_back(rand() % 30);
}
for (unsigned int j = 0; j < 30; j++) {
cout << v[j] << endl;
}
return 0;
}
The classic Fisher–Yates shuffle can also be used to generate a shuffled vector directly, in one pass
vector<unsigned> v;
for (unsigned i = 0; i < 30; ++i)
{
unsigned j = rand() % (i + 1);
if (j < i)
{
v.push_back(v[j]);
v[j] = i;
}
else
v.push_back(i);
}
You should probably generate vector and just shuffle it:
#include <iostream>
#include <ctime>
#include <utility>
int main()
{
std::srand(static_cast<unsigned int>(std::time(NULL)));
size_t const n = 30;
std::vector<int> v(n);
//make vector
for (size_t i = 0; i < n; ++i)
v[i] = static_cast<int>(i);
//shuffle
for (size_t i = n - 1; i > 0; --i)
std::swap(v[i], v[static_cast<size_t>(rand()) % (i + 1)]);
//print
for (size_t i = 0; i < n; ++i)
std::cout << (i > 0 ? "," : "") << v[i];
return 0;
}
Prints, for example:
27,24,2,23,13,6,9,14,11,5,15,18,16,29,22,12,26,20,10,8,28,25,7,4,1,17,0,3,19,21
void selectionSort (vector<string>& dictionary)
{
string min;
for (int i = 0; i < dictionary.size(); ++i)
{
for (int j = i + 1; j < dictionary.size(); ++j)
{
if (dictionary.at(j) < dictionary.at(i))
{
min = dictionary.at(j);
}
}
swap(dictionary.at(i), min);
}
return;
}
I entered 5 inputs: hey, ok, so, no, okay
Outputs: no, okay, so, no
Could someone explain where I went wrong with my sorting function? Thanks!
Try this instead:
void selectionSort(vector<string>& dictionary)
{
for (int i = 0; i < dictionary.size(); ++i)
{
int m = i;
for (int j = i + 1; j < dictionary.size(); ++j)
{
if (dictionary[j] < dictionary[m])
m = j;
}
if (m != i)
swap(dictionary[i], dictionary[m]);
}
}
Basically when your i-loop starts you assume that m-th element is smallest and then inside j-loop you check remaining elements if there is a smaller element. If you find smaller element you update m (instead of copying actual strings). At the end of the loop you check if m is changed from i, and if so you swap elements at i and m.
Here's full example with your input, when asking question it's recommended to provide similar minimal example that can easily reproduce your problem:
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <assert.h>
using namespace std;
void selectionSort(vector<string>& dictionary)
{
for (int i = 0; i < dictionary.size(); ++i)
{
int m = i;
for (int j = i + 1; j < dictionary.size(); ++j)
{
if (dictionary[j] < dictionary[m])
m = j;
}
if (m != i)
swap(dictionary[i], dictionary[m]);
}
}
int main()
{
vector<string> data{ "hey", "ok", "so", "no", "okay" };
vector<string> data2 = data;
selectionSort(data);
std::sort(data2.begin(), data2.end());
assert(equal(data.begin(), data.end(), data2.begin())); // verify that your sort matches what std::sort does
for (const auto s : data)
cout << s << ' ';
cout << endl;
}
and the output is:
hey no ok okay so
int temp;
for (int j = 0; j < vecsize - 1; ++j) {
int min = sort.at(j);
for (int i = j+1; i < vecsize; ++i) {
if (min > sort.at(i)) {
min = sort.at(i);
temp = i;
}
}
swap(sort.at(j), sort.at(temp));
}
I am trying to sort (in ascending order) the vector of: 23 42 4 16 8 15
However, my attempt at using selection sort outputs: 4 8 15 23 16 42
What am I doing wrong?
When you define min, you seem to be assigning it the value of the array sort at jth index. Yet, you are using an extra variable tmp to swap the elements, and you seem to fail to initialize it before the inner for loop, similar to how you initialize min. And if all the other elements in the array are smaller than the element at sort[j], tmp will be uninitialized for that iteration of the outer loop, possibly causing it to have an incorrect value in it.
int temp;
for (int j = 0; j < vecsize - 1; ++j) {
int min = sort.at(j);
temp = j; # HERE'S WHAT'S NEW
for (int i = j+1; i < vecsize; ++i) {
if (min > sort.at(i)) {
min = sort.at(i);
temp = i;
}
}
swap(sort.at(j), sort.at(temp));
}
You may see this code at work here. It seems to produce the desired output.
Try this : corrected-code
#include <iostream>
#include <vector>
using namespace std;
void print (vector<int> & vec) {
for (int i =0 ; i < vec.size(); ++i) {
cout << vec[i] << " ";
}
cout << endl;
}
int main() {
int temp;
vector<int> sort;
sort.push_back(23);
sort.push_back(42);
sort.push_back( 4);
sort.push_back( 16);
sort.push_back( 8);
sort.push_back(15);
print(sort);
int vecsize = sort.size();
for (int j = 0; j < vecsize - 1; ++j) {
int min = j;
for (int i = j+1; i < vecsize; ++i) {
if (sort.at(min) > sort.at(i)) {
min = i;
}
}
if (min != j)
swap(sort.at(j), sort.at(min));
}
print(sort);
return 0;
}
If you can use C++11, you can also solve sorting (as in your example) with lambdas. It's a more powerful and optimized way. You should try it maybe in the future.
[EDITED]:
A short example:
// Example program
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> myVector;
myVector.emplace_back(23);
myVector.emplace_back(42);
myVector.emplace_back(4);
myVector.emplace_back(16);
myVector.emplace_back(8);
myVector.emplace_back(15);
std::sort(myVector.begin(), myVector.end(),
[](int a, int b) -> bool
{
return a < b;
});
}
I have the code below and I'm strugling to add values to the vector. The end goal is to itterate through a list and for each itteration add a value to 2 rows of a vector but I'm strugling to understand how to push_back to a 2d vector.
std::vector<std::vector<int> >nns;
int i = 5;
nns.push_back(i, i);
for(int i = 0; i <nns.size(); i++)
{
for(int j = 0; j < nns[i].size(); j++)
{
std::cout << nns[i][j] << std::endl;
}
}
How would I add one column to this vector?
so
vector[0][0] = 0
vector[1][0] = 0?
Answer provided by Algirdas Works perfectly.
#include <iostream>
#include <vector>
using namespace std;
int main() {
std::vector<std::vector<int> > nns;
int i = 5;
nns.push_back(std::vector<int>{i});
for (int i = 0; i < nns.size(); i++) {
for (int j = 0; j < nns[i].size(); j++) {
std::cout << nns[i][j] << std::endl;
}
}
}
I have this function meant to initialize a multidimensional 2d (6x6) array to zero. I call the function in main using cout to test it and it outputs garbage. Please help. Thanks!
int** initializeArray(void)
{
typedef int* rollArray; //this line is actually outside of the function in my
//program
int i, j;
rollArray *m = new rollArray[6];
for (i = 0; i < 6; i++)
m[i] = new int[6];
for (i = 0; i < 6; i++)
for (j = 0; j < 6; j++)
m[i][j] = 0;
return m;
}
If the value 6 is known at compile-time, I would suggest using std::array in a nested fashion. For example:
#include <array>
#include <iostream>
int main()
{
std::array<std::array<int,6>,6> a = {0};
for (int i = 0; i < 6; ++i)
{
for (int j = 0; j < 6; ++j)
{
std::cout << a[i][j] << std::endl; // Prints 0.
}
}
return 0;
}
In fact, you won't even need to create a function to initialize your array. Declare your nested array and you are good to go. (If you don't know the dimension at compile-time, you could use std::vector in a similar fashion.)
The problem is with your test.
How can you mess up such a simple test? Just use:
int ** a = initializeArray();
int i,j;
for (i = 0; i < 6; i++) {
for (j = 0; j < 6; j++) {
cout << a[i][j] << " ";
}
cout << endl;
}