Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: How do you sort an array? [using bubble sort]

1. ## How do you sort an array? [using bubble sort]

Here's my code:
```import java.util.*;

class array1{
public static void main(String args[]){
Random number = new Random();

int num[] = new int[100];

// filling array with random numbers
for(int i=0;i<100;i++){
int randomnumber = 10+number.nextInt(89);
num[i] = randomnumber;
System.out.print(num[i]+" ");
}
// Sorting the array
for(int i=0;i<100;i++){
for(int j=0;j<100;j++){
if(num[j]>num[j+1]){
num[j]=num[j+1];
num[j+1]=num[j];

}
}
}
}
}```
What should I put after the "num[j+1]=num[j]"?

2. ## Re: How do you sort an array? [using bubble sort]

This:
```num[j]=num[j+1];
num[j+1]=num[j];```
Will not swap values. For example, let's say:
num[j]=10
num[j+1]=12
After we run the first line of code, the values become:
num[j]=12
num[j+1]=12
And after we run the second line of code, the values stay:
num[j]=12
num[j+1]=12

Why? Because we never "remembered" the previous value of num[j]