Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Sorter

  Asked By: Richard    Date: Jul 12    Category: Java    Views: 592
  

This code, why it doesn't give the correct output?
The code is supposed to sort the values stored in a vector in ascending
order.
For example, we have a vector "4,2,3,1", and we want the output to be in
order "1,2,3,4".
Also, do you have any other way of doing this?

How do we get the correct output??

public class Tester{
public static void main(String[] args){
int temp=0;
int[] v={4,2,3,1};
System.out.println(v);
for (int i=1; i<v.length;i++)
{
for (int j=1; j<v.length-i;j++)
{
if (v[j+1]>v[j])
temp=v[j+1];
v[j+1]=v[j];
v[j]=temp;
}
}
System.out.println(v);
}
}

Share: 

 

1 Answer Found

 
Answer #1    Answered By: Chau Tran     Answered On: Jul 12

I noticed that someone else posted a answer that looks just about right
... But I have a couple of pointers for you.

First of all you change bracketing inside your class  file i.e. you start
off with ...

> public class Tester{
>
> public static  void main(String[] args){

Bracketing that comes after your method decleration and then you ...

> for (int i=1; i<v.length;i++)
>
> {

Change to putting the bracket underneath the begining of the method
decleration.

Now both methods are good, just not in the same class file. It makes it
easier to get confused about what brackets are where.

>
> if (v[j+1]>v[j])
>
> temp=v[j+1];

This is a perfect example  of why you should never realy put a if
statement on a second line unless it is in {} blocks. I mean technicaly
there isn't a problem with it, but it is so easy to put a new line in,
or make a space (like you did) and it just breaks everything.

I now force myself to either write it all on one line

if (someStuff) doStuff();

If for some reason I can't I put it in a {} block

if (someStuff){
doStuff();
}

It might add lines to your code, but it always places bets on the safe
side of coding. While not doing it can harm readablity and can make it
dangerous.

It isn't the worst habit you can do, and realy you can make you own
decision on if you want to do it or not.

It is my experiance however that it constantly bites you on the bum.

 
Didn't find what you were looking for? Find more on Sorter Or get search suggestion and latest updates.

Related Topics:



Tagged:  

 

Related Post