topper1309 topper1309 - 1 year ago 87
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>();

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)){
for(int s:v)
System.out.print(s + " ");


Entered: 2

Entered: 98

Entered: 3

Entered: 10

Entered: 1

2 5 3 10 1 98

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download