topper1309 topper1309 - 24 days ago 10
Java Question

How to sort number when entering vector in java

I want to add numbers in sorted way before entering vector. But the result is not right and I am confused where the problem is ? Output is shown below.

I want to sort using some algorithm without any inbuilt methods.

import java.util.Vector;

public class Test {
public static void main(String ar[]){
//Numbers to enter in vector
int[] number = {5,2,98,3,10,1};

Vector<Integer> v = new Vector<Integer>();

v.add(number[0]);
for(int i=1;i<number.length;i++){
for(int j=v.size();j>0;j--){
System.out.println("Entered: "+number[i]);
if(number[i] <= v.get(j-1)){
v.add(j-1,number[i]);
break;
}else{
v.add(j,number[i]);
break;
}
}
}
for(int s:v)
System.out.print(s + " ");
}
}


OUTPUT:

Entered: 2

Entered: 98

Entered: 3

Entered: 10

Entered: 1

2 5 3 10 1 98

Answer

You have a second (inner) for loop based on the variable j, but that "loop" will only execute exactly one time. Both conditions inside the j loop cause the loop to exit (break;).

When you're adding each number, the only possibilities are last or next to last.