Skip to content

Selection Sort

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
26
27
28
29
30
31
32
33
34
35
36
37
38
//*****************************************************************
// We simply introduce Selection Sort
//*****************************************************************
import java.util.Random;
public class SelectionSort{
    public static void main(String [] HAHA){
	//Create an object of random class
	Random generator = new Random();
	//Creating an integer array of size 10
	int list [] = new int [10];
	//Putting random numbers into the array we've created
	for(int i=0;i<10;i++)
	    list[i] = generator.nextInt(1000);//We put 1000
	    //because we want integers range from 0 to 1000
	for(int i=0;i<list.length-1;i++){
	     int location = i;//To specify the location of the loop
	     int max = list[i];//We specify the maximum number
	     //We choose the arrays ith element since it can be the
	     //maximum number.
	     for(int j=i;j<list.length;j++){
		 //We compare max and list[j] if max is less we make
		 //it the list[j] because we want maximum element
		 if(list[j]>max){
		      max = list[j];
		      location = j;
		 }
	     }
	     //We create a temprorary integer in order not to lose the
	     //data in list[i] then we change the data between them.
	     int temp = list[i];
	     list[i] = list[location];
	     list[location]= temp;
	}
	//We simply list the array
	for(int i=0;i<list.length;i++)
	    System.out.println(list[i]+"\t");
    }
}

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *