Sort an array by using function in C++ [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 months ago.
Improve this question
I want to make a sort statement by using a function. The problem is, I cannot return it back to the main() function. What's the problem? I also tried the void.
int sort_func(int sort[]) {
int swap = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 4; i++) {
if (sort[j] > sort[j + 1]) {
swap = sort[j];
sort[j] = sort[j + 1];
sort[j + 1] = swap;
}
}
}
return sort[5];
}
What is the problem in the code?

You don't need to return anything. The array is being passed into the function via an int* pointer, so the code is directly manipulating the elements of the caller's array.
Also, your 2nd for loop is incrementing i when it should be incrementing j instead.
How is the caller's array declared, exactly? The loops inside your function require the sort parameter to point at an int[] array with at least 5 elements. However, the function's declaration does not convey or enforce that requirement, so the caller is free to pass in however many elements it wants, and if that size is fewer than 5 then your code will have undefined behavior. You should at least have the caller pass in the actual number of elements as another parameter, eg:
void sort_func(int sort[], int size) {
int swap = 0;
for (int i = 0; i < size; i++) {
for (int j = 0; j < (size-1); j++) {
if (sort[j] > sort[j + 1]) {
swap = sort[j];
sort[j] = sort[j + 1];
sort[j + 1] = swap;
}
}
}
}
int arr[5];
...
sort_func(arr, 5);
Otherwise, if you strictly require 5 elements, then enforce that by taking a pointer to an array with exactly 5 elements, eg:
void sort_func(int (*sort)[5]) {
int swap = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 4; j++) {
if ((*sort)[j] > (*sort)[j + 1]) {
swap = (*sort)[j];
(*sort)[j] = (*sort)[j + 1];
(*sort)[j + 1] = swap;
}
}
}
}
int arr[5];
...
sort_func(&arr);
Or, use a reference instead of a pointer, eg:
void sort_func(int (&sort)[5]) {
int swap = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 4; j++) {
if (sort[j] > sort[j + 1]) {
swap = sort[j];
sort[j] = sort[j + 1];
sort[j + 1] = swap;
}
}
}
}
int arr[5];
...
sort_func(arr);

Related

Multidimensional Arrays initialized,What is differnce of Initialize with declarations and Initialize after declaration?

What is the difference of multidimensional array initialization?
This is 'Longest Common Subsequence' problem.
string str1, str2;
getline(cin, str1);
getline(cin, str2);
int alphaCount[26] = { 0, };
int str1Len = str1.length();
int str2Len = str2.length();
int** arr = new int* [str1Len+1];
for (int i = 0; i < str1Len+1; i++)
{
arr[i] = new int[str2Len+1];
//Method One
for (int j = 0; j < str2Len+1; j++)
{
arr[i][j] = 0;
}
}
for (int i = 0; i < str1Len; i++)
{
for (int j = 0; j < str2Len; j++)
{
int y = i + 1;
int x = j + 1;
if (str1[i] == str2[j])
arr[y][x] = arr[y - 1][x - 1] + 1;
else
{
if (arr[y][x - 1] > arr[y - 1][x])// using uninitialized memory ERROR
arr[y][x] = arr[y][x - 1];
else
arr[y][x] = arr[y - 1][x];
}
}
}
cout << arr[str1.length()][str2.length()] << "\n";
// Method Two
// Not Error
for (int i = 0; i < str1Len + 1; i++)
{
for (int j = 0; j < str2Len + 1; j++)
{
arr[i][j] = 0;
}
}
// Method Three
//global valiable, Not Error
int arr[1001][1001];
Why Method One has error message
warning C6001: using uninitialized memory .
What is the difference between method 1 and method 2?
If there are more elements than numbers in the list, C++ pads the list with zeros. Thus this static array:
int alphaCount[26] = { 0, };
will have all its members initialized to zeroes (explicitly setting the first element to zero, and letting the others get automatically initialized).
This:
int** arr = new int* [str1Len+1];
for (int i = 0; i < str1Len+1; i++)
{
arr[i] = new int[str2Len+1];
for (int j = 0; j < str2Len+1; j++)
{
arr[i][j] = 0;
}
}
will also initialize all elements of the array to 0. However, in this case, the array is a 2D array, and is dynamically allocated (don't forget to free it afterwards). Typically you should check if new succeeded.
Note: Static array vs. dynamic array in C++.
The second method will initialize all the elements of the 2D array to zero, by using a double for loop.
The third method will initialize the global array's elements to zeroes, since Why are global and static variables initialized to their default values?

C++ 2d static array and memory allocation

I think, I have just made a mistake: I was allocating a static 2D array and accessing it as 1 dimension.
Could you tell me how bad it is - method geta?
The code below works fine on my Windows, and Linux: actual is always eqauls to expected and stride is always equals to N.
#include "stdafx.h"
#define N 2000
int a[N][N];
int geta(int i, int j) {
return *(a[0] + i * N + j);
}
int main()
{
printf("Hello\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
a[i][j] = i + j;
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
int const expected = a[i][j];
int const actual = geta(i, j);
if (actual != expected) {
printf("wrong data at [%d,%d] expected=%d actual=%d", i, j, expected, actual);
}
}
}
for (int i = 1; i < N; i++) {
int stride = a[N] - a[N - 1];
if (stride != N) {
printf("wrong: i=%d c=%d N=%d", i, stride, N);
}
}
return 0;
}
Could you tell me how bad it is - method geta?
Bad. But correct. C++ guarantees memory for a to be contiguous and the memory layout to be row major, so your code returns in a correct manner the expected element. Let's see how:
The type of a[0] is int[2000] 1) . But as soon as you do arithmetic on it it decays, i.e. int*. So +i*N moves the pointer to the (beginning of the) line i and +j moves the pointer to the column j.
1) actually it's int(&)[2000] but not that relevant here

Implement Hash Tables separate chaining with vectors

Does anyone know how to add a vector into an array?
I'm given a array table but to solve collisions, i need to implement vectors.
I am provided with this code:
void generateTable(string DNA, int N, int K, int *&table) {
int tableSize = 1;
for (int i = 0; i < K; i++)
table[i] = 0;
I had planned to implement the hashing as such:
for(int i = 0; i < N - K; i++) {
temp = DNA.substr(i, K);
for (int j = 0; j < K; j++) {
value = value * 10 + convert(temp[j]) //this is just to convert the substr into int.
if (table[value % tableSize] == 0)
table[value % tableSize] = value;
else {
//this is where i plan to use vectors to solve collisions
thank you so much for your help. Do let me know if there is any confusion about my question

Storing 1D array to 2D

How can I store a 1D array of 9 into a 2D array of 3x3? This is my current attempt:
for (j = 0; j < 3; j++)
{
if (i = 0)
{
a[i][j] = (int)data1[j];
}
if (i = 1)
{
a[i][j] = (int)data1[j + 3];
}
if (i = 2)
{
a[i][j] = (int)data1[j + 6];
}
}
}
something like this:
for (int i = 0; i < 9; i++)
{
a[i / 3][i % 3] = data[i];
}
And as ThisHandleNotInUse pointed out, MAYBE this one is more optimized depending on the circumstances and still scales to larger arrays with minor tweaking.
for (int i = 0; i < 9; i += 3)
{
for (int j = 0; j < 3; j++)
{
a[i][j] = data[i + j];
}
}
First of all. Logical equal sign must be written like this:if (i == 0)
This will check condition.
if (i=0)
Is not correct because you do assignement operator for i
You can try this:
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
if(i == 0)
{
a[i][j] = (int)data1[j];
}
if (i == 1)
{
a[i][j] = (int)data1[j+3];
}
if (i == 2)
{
a[i][j] = (int)data1[j+6];
}
}
}
If you are coding in c++, if(I=2) is incorrect it should be if (I==2) and I'm not sure why you need that
One possible solution is to have two nested for loops as you already have and this code: a[i][j]=data[j*3+i]. No if is needed then.
How optimized do you need this to be? What does your array contain? If your array contains structs, you're going to be copying them no matter what you do. If it contains references, you're going to be copying them (the references) no matter what you do.
If I were regularly converting an array[9] to an array[3,3], I'd just do this:
(arr = Old Array)
Array[,] NewArr = new Array[,]{ { arr[0], arr[1], arr[2] }, {arr[3], arr[4], arr[5]}, {arr[6], arr[7], arr[8]} };
EDIT: commenter below pointed out you were using a jagged array and not a multidimensional one in which case, in C#, the syntax would be:
Array[][] NewArr = new Array[][]{ new Array[]{ arr[0], arr[1], arr[2] }, new Array[]{ arr[3], arr[4], arr[5]}, new Array[]{ arr[6], arr[7], arr[8] } };

Nested loop with arrays having repeating numbers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have an array that keeps the number of each element.
int total[5] = {2,3,4,5,6}
int num = 5; //array total has 5 elements
This means that we have 2 element 0's, 3 element 1's in our original array. We are not worried about the original array since I already have a code to keep the number of the elements.
I need a nested for loop that creates a new array that looks like this:
array[0] = 1;
array[1] = 1;
array[2] = 5;
array[3] = 5;
array[4] = 5;
array[5] = 9;
array[6] = 9;
array[7] = 9;
array[8] = 9;
and so on. That is, we store a value in our new array as many as the its value in "total" array. Values 1,5,9, etc. are stored in an array called element. I have something like this so far:
for (int i = 0; i < num; i++){
for (int j = 0; j < total[i]; j++){
array[i + j] = element[i];
}
}
Can somebody help me to figure this out?
An easy solution (though not necessarily elegant) is to do the following:
int count = 0;
for (int i = 0; i < num; i++){
for (int j = 0; j < total[i]; j++){
array[count] = element[i];
count++;
}
}
then you don't need to worry about trying to figure out what position you are at for the array.
You need to track the number of the elements:
int sum = 0;
for (int i = 0; i < num; i++){
for (int j = 0; j < total[i]; j++){
array[sum + j] = element[i];
}
sum += total[i];
}