Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
So, yesterday my teacher gave us a question to try. The link for the question is
Rearrange an array such that arr[i] = i - GeeksforGeeks[^]
He just told the problem and the input and told us to try. I came up with a solution and showed it to him.
But, he said that my code is bad and not optimised. After some time, he showed the code (first one) that is given in the website in a projector and said it is the correct solution.
Basically, my code and the code in the website works.
But I need to know why he said that my code is not optimised and bad. How can I improve myself to write good code.

What I have tried:

#include<stdio.h>
int main()
{
        int a[] = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1},n,i,x,y;
        n= sizeof(a)/sizeof(a[0]);
        for(i=0;i<n;i++){
                if(a[i] == i || a[i] == -1)
                        continue;
                else if(a[i] != -1){
                                x=a[i];
                                y=a[x];
                                a[i] = y;
                                a[x] = x;
                }
        }
        for(i=0;i<n;i++)
                printf("%d ",a[i]);
}

~                                                                                                                                                                    
~                                                                                                                                                                    
~                                                                                                                                                                    
~                      
Posted
Updated 1-Feb-19 22:58pm
Comments
Richard Deeming 4-Feb-19 12:35pm    
Why don't you ask your teacher to explain it to you? That's what he's paid to do! :)
Kohila G 9-Feb-19 13:35pm    
Really Bad social anxiety.

1 solution

I see three reasons

1.you check for
a[i] == -1
so in the else you neednt a check against it.

2. you have 2 n-loops

3. you need one assignment less.
C++
x=a[i];
a[i]=a[x];//direct without buffering
a[x] = x;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900