This java
program sorts an array using selection sort technique. First enter the
length of array using keyboard, after that enter the elements of array. Now,
compare the elements of array and if first element is greater than second
element, then perform swapping.
Selection Sort in Java
import java.util.Scanner;
class SelectionSort
{
public static void main(String[] args) {
int length, i, j, temp;
System.out.print("Enter the Length of Array : ");
Scanner sc = new Scanner(System.in);
length = sc.nextInt();
int arr[] = new int[length];
System.out.print("Enter Array Elements : ");
for(i=0; i<length; i++)
{
arr[i] = sc.nextInt();
}
for(i=0; i<length; i++)
{
for(j=i+1; j<length; j++)
{
if(arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.print("Sorted Array : ");
for(i=0; i<length; i++)
{
System.out.print(arr[i]+ " ");
}
}
}
Output:
Enter the Length of Array : 5
Enter Array Elements : 8 6 7 1 2
Sorted Array : 1 2 6 7 8
0 comments:
Post a Comment