In: Computer Science
There's an array named score, 90, 98, 92, 88, 100, 80 are the elements in this array.
Please write a Java program to declare and sort this array (use selection sort).
Code:
public class Main
{
public static void selectionSort(int[] array){ //method of
selection sort
for(int i=0;i<array.length-1;i++)
{
int index=i;
for(int j=i+1;j<array.length;j++)
{
if (array[j]<array[index])
{
index=j; //searching for lowest index
}
}
int smallerNumber = array[index];
array[index] = array[i];
array[i] = smallerNumber;
}
}
public static void main(String[] args) {
int [] score =
{90,98,92,88,100,80}; //declare and initialize array named
score
selectionSort(score); //sorting array using selection sort by
calling selectionSort function
System.out.println("Result after Selection Sort");
for(int i=0;i<score.length;i++) //print array after sort
{
System.out.print(score[i]+" ");
}
}
}
Output: