Arrays

Usually we use an array because we want to access the array in a different order.

The program below reads in three numbers, sorts them, then prints them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//Arrays: Read 3 numbers, sort and print
package numbers;
import java.util.*;
public class Numbers { 
  public static void main(String[] args) {
	  Scanner keyboard=new Scanner(System.in); 
	  double[] num= new double[3];
	  for(int i=0;i<3;i++){
		  System.out.print("Enter a number:"); 
		  num[i]=keyboard.nextDouble();
	  }//for loop to input
	  if (num[0] > num[1]) swap(num,0,1);
	  if (num[1] > num[2]) swap(num,1,2);
	  if (num[0] > num[1]) swap(num,0,1);
	  for(int i=0;i<3;i++){
		  System.out.println(num[i]); 
	  }//for loop to output
  }//main
  public static void swap(double d[],int i, int j){
	//swap elements i and j
    double temp=d[i];
	d[i]=d[j];
	d[j]=temp;
  }//swap
}//class
CODE

It is important to note that Java always passes primitive variables by value. Objects and arrays are passed a reference to the address.

In this program the reference to the array is passed to swap, but the values 0 and 1 are passed.

This algorithm works for just 3 numbers. You will study other algorithms for sorting large arrays.

NEXT: