• Post Reply Bookmark Topic Watch Topic
  • New Topic

Second smallest element in an array  RSS feed

 
Shubham Semwal
Ranch Hand
Posts: 176
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, below is the code for finding second smallest element in an array.


This is working fine. But if the array's smallest element is in index 0 then this code doesn't work.
How can I fix this ? Or is there a more efficient algorithm.
 
Junilu Lacar
Sheriff
Posts: 11164
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Line 7 is essentially saying that you're assuming that the first element is also the second smallest. This initial assumption cannot be corrected properly by the logic in your loop if the first element is actually the smallest. So you need to change your initial assumption. Here are some more conditions to consider:
1. Array elements are all the same number.
2. Array only has one element
 
Shubham Semwal
Ranch Hand
Posts: 176
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. That was a blunder. I was just assigning something and wasn't thinking logically that the smallest element can't be the second smallest lol.
 
Campbell Ritchie
Marshal
Posts: 55761
163
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot sort out that kind of question in code. You have to get a pencil and paper and work it out first. You will also need a eraser. Preferably a large one!
 
Stevens Miller
Bartender
Posts: 1444
30
C++ Java Netbeans IDE Windows
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:You cannot sort out that kind of question in code. You have to get a pencil and paper and work it out first. You will also need a eraser. Preferably a large one!

Back in the '70s, one of the first books I read on coding contained a glossary. Here's an entry I will always remember:
Optimist = programmer who codes in ink.
 
Liutauras Vilda
Marshal
Posts: 4657
319
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can have a look at this Stevens's post (<- link) for the same problem, so you'd see how powerful can be simple techiques.

Solution seems reasonably easy when you get that solved on a piece of paper
 
Shubham Semwal
Ranch Hand
Posts: 176
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. Need to do things in paper first.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!