bubble sort ideone time limit exceeded - c

#include <stdio.h>
int main(void) {
int a[5]={1,2,0,5,4},i,j,c;
for(i=0;i<5;i++)
{
for(j=0;j<5-i;j++){
if(a[j]>a[j+1])
{
c=a[j];
a[j]=a[j+1];
a[j+1]=c;
}
}
}
for(i=0;i<5;i++)
{
printf("%d",a[i]);
}
return 0;
}
ideone says "Time limit exceeded time: 5 memory: 2048 signal:24"
but it works fine on turbo compiler

for(j=0;j<5-i;j++){
if(a[j]>a[j+1])
a[j+1] is array out of bound access which will lead to undefined behavior

Try this for bubble sort..Machine cycle will not be hampered in any compilers..
for (i = 0; i < count -1; i++)
for (j = 0; j < ((count - 1) - i); j++) {
if (memptr[j]>memptr[j+1]) {
temp = memptr[j];
memptr[j] = memptr[j + 1];
memptr[j + 1] = temp;
}
}

int a[5]={1,2,0,5,4}
So, for the following index you will get the following content:
index ->| 0 | 1 | 2 | 3 | 4 |
content ->| 1 | 2 | 0 | 5 | 4 |
Now In your outer loop for(i=0;i<5;i++), for the first iteration i = 0, then the inner loop breaking condition will be,
for(j=0;j<5-i;j++)
or,
for(j=0;j<5-0;j++)
Hence the value of j will increase 0 to 4.
Now think what will happen a[j+1], when j = 4!
You are trying to access, a[4+1] or, a[5] where the index of array a is defined up to 4.
So at a[5], you will get Undefined behavior.
Try:
for(j=0; j<5 -i -1; j++)

Related

Why my table is not displayed if I do not put it [i]

I would like to know what the [i] is for, and why my table is not displayed if I do not put it in.
Thank you!
#include <stdio.h>
void affiche(int* tableau, int taille);
int main()
{
int tableau[5] = { 12,15,50,20 };
affiche(tableau, 4);
return 0;
}
void affiche(int *tableau,int taille)
{
int i;
for (i = 0; i < taille; i++)`
{
printf("%d\n", tableau[i]);
}
}
[i] is the C language syntax for array notation.
tableau is an array of 5 integers.
int tableau[5] = {12,15,50,20}
In memory tableau has 5 slots allocated to it due to the above declaration.
Slots 0 through 3 are your initialization values.
Slot 4 is uninitialized (though modern c compilers might set this value to null or zero (0).
tableau
+-----------------------+
index | 0 | 1 | 2 | 3 | 4 |
+-----------------------+
value | 12 | 15 | 50 | 20 | ? |
+-----------------------+
inside function affiche(...) this statement
printf("%d\n", tableau)
tries to print to console a single integer (%d) followed by a newline (\n)
But tableau is an array of 5 integers.
So you need the array index to select a specific integer individually like this:
printf("%d\n", tableau[0]) // output: 12
printf("%d\n", tableau[1]) // output: 15
printf("%d\n", tableau[2]) // output: 50
printf("%d\n", tableau[3]) // output: 20
printf("%d\n", tableau[4]) // output: unknown, possible exception
or by function call to affiche(tableau, 4); which ends at index 3
void affiche( int *tableau, int taille)
{
int i;
for( i = 0; i < taille; i++){
printf( "%d\n", tableau[i] );
}
}
Which outputs:
12
15
50
20

C[i] = A[i++]; is not equal to C[i] = A[i]; i++; Whats going on here? [duplicate]

This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 3 years ago.
I tried looping over an array in different ways using loop unrolling.
#define MYSIZE 8
int main()
{
int A[MYSIZE];
int B[MYSIZE];
int C[MYSIZE];
int i = 0;
while(i < MYSIZE)
{
A[i] = i;
i++;
}
/* LOOP 1 */
i = 0;
while (i< MYSIZE)
{
B[i+0] = A[i+0];
B[i+1] = A[i+1];
B[i+2] = A[i+2];
B[i+3] = A[i+3];
i += 4;
}
/* LOOP 2 */
i = 0;
while (i < MYSIZE)
{
C[i] = A[i++];
C[i] = A[i++];
C[i] = A[i++];
C[i] = A[i++];
}
printf(" i | A | B | C|\r\n");
i = 0;
while (i < MYSIZE)
{
printf(" %d | %d | %d | %d |\r\n",i,A[i],B[i],C[i]);
i++;
}
}
Which does give me this result:
i | A | B | C |
0 | 0 | 0 | 1578166688 |
1 | 1 | 1 | 0 |
2 | 2 | 2 | 1 |
3 | 3 | 3 | 2 |
4 | 4 | 4 | 3 |
5 | 5 | 5 | 4 |
6 | 6 | 6 | 5 |
7 | 7 | 7 | 6 |
I thought that A,B and C should contain the same numbers.
As I understood i++, LOOP 2 should be the same as:
/* LOOP 3 */
i = 0
while(i < MYSIZE)
{
C[i] = A[i];
i++;
C[i] = A[i];
i++;
C[i] = A[i];
i++;
C[i] = A[i];
i++;
}
Which is not the case. LOOP 3 actually works fine but LOOP 2 does not. What am I doing wrong ?
This expression:
C[i] = A[i++];
Invokes undefined behavior because the variable i is both read and written without a sequence point.
While it is true that the right hand side of an assignment must be fully evaluated before it can be assigned to the left side, the evaluation of each subexpression is unsequenced, as is the side effect of i being incremented.
This is spelled out in section 6.5.16p3 of the C standard regarding the assignment operator:
An assignment operator stores a value in the object designated by the left operand. An
assignment expression has the value of the left operand after the assignment, but is not
an lvalue. The type of an assignment expression is the type the left operand would have
after lvalue conversion. The side effect of updating the stored value of the left operand is
sequenced after the value computations of the left and right operands. The evaluations of
the operands are unsequenced.
In this specific example, the value of i could first be read to use as the index of C, then it could be read and written as part of the i++ expression on the right side. Alternatively, i++ could be evaluated first and incremented, and then i could be read to be used as the index of C.
The increment of i should be done as part of a separate statement to avoid this.
C[i] = A[i];
i++;
With dbush's response, I did a test using an additional variable to avoid the incidence and I got the expected result.
/* LOOP 2 */
i = 0;
int j = 0;
while (i < MYSIZE)
{
C[j++] = A[i++];
}

Generating increasing subsequences out of n numbers of length k

I want to generate all possible increasing subsequences of numbers (repetition allowed) from 1 to n, but of length k.
Ex. n=3, k=2
Output:
1 1
1 2
1 3
2 2
2 3
3 3
This is my code:
#include <stdio.h>
int s[100];
int n=6;
int k=4;
void subk(int prev,int index)
{
int i;
if (index==k)
{
for(int i=0; i<k; i++)
printf("%d ",s[i]);
printf("\n");
return;
}
s[index]=prev;
for (i=prev; i<=n; ++i)
{
subk(i,index+1);//,s,n,k);
}
}
int main()
{
int j;
for (j = 1; j<=n ; ++j)
{
subk(j,0);
}
return 0;
}
But this generates some unwanted repetitions. How do I eliminate those?
I have tested your code with n = 3 and k = 2 and got the following result:
1 1
1 1
1 1
1 2
1 2
1 3
2 2
2 2
2 3
3 3
This is obviously incorrect, as there are several identical numbers like 1 1 or 1 2.
But what exactly went wrong?
Let's write down the right results if n = 3 and k = 3. Now compare those to the result we got from the program when n = 3 and k = 2.
correct program (incorrect)
k = 3 k = 2
1 1 1 1 1
1 1 2 1 1
1 1 3 1 1
1 2 2 1 2
1 2 3 1 2
1 3 3 1 3
2 2 2 2 2
2 2 3 2 2
2 3 3 2 3
3 3 3 3 3
Now we can see that the incorrect output of the program is the same as the first two columns of the correct answer when we set k = 3. This means that the program solves the problem for 3 columns if we set k = 2, but only displays the first two columns.
You need to stop the program from writing the same number several times.
Solution 1
One way to do this is to execute the for-loop in the subk-function only once when it writes the last number (index == (k - 1)) into the buffer s.
In order to achieve this, you need to add the following two lines to the end of your for-loop.
if (index == (k - 1))
break;
(Instead of the break you could also use return)
After you added these two lines the function should look like this:
void subk(int prev, int index)
{
int i;
if (index == k)
{
for (int i = 0; i<k; i++)
printf("%d ", s[i]);
printf("\n");
return;
}
s[index] = prev;
for (i = prev; i <= n; ++i)
{
subk(i, index + 1);//,s,n,k);
if (index + 1 == k)
break;
}
}
Solution 2
Another way to solve the problem is to move the line s[index] = prev; to the beginning of the function and change the k in the if-statement to k - 1.
Now the function should look like this:
void subk(int prev, int index)
{
int i;
s[index] = prev;
if (index == k - 1)
{
for (int i = 0; i<k; i++)
printf("%d ", s[i]);
printf("\n");
return;
}
for (i = prev; i <= n; ++i)
{
subk(i, index + 1);//,s,n,k);
}
}
With this solution, the for-loop is never executed when the index shows that the program is at the last 'sub-number'. It just displays the number and exits the function because of the return.
You get the right result with both solutions, but I personally like the second solution better, because there is no additional if-statement that is executed every iteration of the for-loop and the program is (slightly) faster.

Why is my program not dividing even numbers by two?

It should scan 10 int numbers and then display them backwards, dividing the even ones by two, but it just displays them without dividing.
es:
10 9 8 7 6 5 4 3 2 1 ==> 1 2 3 2 5 3 7 4 9 5
but mine does:
10 9 8 7 6 5 4 3 2 1 ==> 1 2 3 4 5 6 7 8 9 10
#include <stdio.h>
int main(void)
{
int a[10];
for(int i = 0; i < 10; i++)
scanf("%d", &a[i]);
for (int i = 0; i < 10; i++) {
if (a[i] % 2 == 0 ) {
a[i] = a[i] / 2; i++;
}
else
i++;
}
for(int i = 9; i > -1; i--)
printf("%d\n", a[i]);
return 0;
}
The middle loop incorrectly increments i twice per iteration:
for (int i = 0; i < 10; i++) { // <<== One increment
if (a[i]%2 == 0 ) {
a[i] = a[i]/2; i++; // <<== Another increment - first branch
}
else
i++; // <<== Another increment - second branch
}
In your case, all even numbers happen to be stored at even positions that your loop skips.
Note: A better solution is to drop the middle loop altogether, and do the division at the time of printing.
The body of your second for loop advances i. Since it's also advanced in the loop's clause, it's advanced twice, effectively skipping any other element. Remove those advancements, and you should be OK:
for(int i=0; i<10; i++) {
if (a[i] % 2 == 0) {
a[i] /= 2;
}
}
In your program you incrementing the for loop variable i two times inside the loop and loop also increment the value one time so the values are skipped that is the reason you are getting wrong output.herewith i have attached the corrected program and its output.hope you understand the concept .Thank you
#include <stdio.h>
int main(void)
{
int a[10];
printf("\n Given Values are");
printf("\n-----------------");
for(int i = 0; i < 10; i++)
scanf("%d", &a[i]);
for (int i = 0; i < 10; i++)
{
if (a[i] % 2 == 0 )
{
a[i] = a[i] / 2;
}
}
printf("\n After dividing the even numbers by 2 and print in reverse order");
printf("\n ----------------------------------------------------------------\n");
for(int i = 9; i > 0; i--)
printf("%d\n", a[i]);
return 0;
}
Output
Given Values are
-----------------
1
2
3
4
5
6
7
8
9
10
After dividing the even numbers by 2 and print in reverse order
----------------------------------------------------------------
5
9
4
7
3
5
2
3
1

Solving #1015 (Brush) in LightOJ

I am trying to solve the following problem.
Input
Input starts with an integer T (≤ 100), denoting the number of test cases.
Each case starts with a blank line. The next line contains an integer N (1 ≤ N ≤ 1000), means that there are N students. The next line will contain N integers separated by spaces which denote the dust unit for all students. The dust unit for any student will not contain more than two digits.
Output
For each case print the case number and the total required dust units.
Sample Input
+--------------+-------------------------+
| Sample Input | Output for Sample Input |
+--------------+-------------------------+
| 2 | Case 1: 16 |
| | Case 2: 100 |
| 3 | |
| 1 5 10 | |
| | |
| 2 | |
| 1 99 | |
+--------------+-------------------------+
Here is my code:
#include <stdio.h>
int main() {
int kase = 0;
int i = 0, j = 0;
do {
scanf("%d", &kase);
} while (kase > 100);
int group[kase];
int tdust[kase];
for (i = 1; i <= kase; i++) {
tdust[i] = 0;
printf("\n");
do {
scanf("%d", &group[i]);
} while (group[i] < 1 || group[i] > 1000);
int stdNumber[group[i]];
for (j = 1; j <= group[i]; j++) {
do {
scanf("%d", &stdNumber[j]);
} while (stdNumber[j] >= 100);
tdust[i] = tdust[i] + stdNumber[j];
}
}
for (i = 1; i <= kase; i++)
printf("\nCase %d: %d", i, tdust[i]);
}
When I submit my code, OnlineJudge says I've got the wrong answer. How can I fix it?
You are getting WA because your code exhibits UB(Undefined Behaviour). You assume that the valid indices for an array of length n where n is a natural number, starts from 1 and ends at n. That is wrong.For an array of length n(n is a natural number), Array indices start from 0 and end at n-1.
To fix it, change
for(i=1; i<=kase; i++)
To
for(i=0; i<kase; i++)
And similarly,do the same for all the other loops. Also change
printf("\nCase %d: %d",i,tdust[i]);
To
printf("\nCase %d: %d",i+1,tdust[i]);
So that you get the desired result.

Resources