Selection Sort
Selection Sort
Design and implement a program in Java that uses simple technique to sort n
elements using selection sort.
import java.util.Random;
import java.util.Scanner;
public class SelectionSort {
static int sortcount=0;
public static void selSort(int[] a) {
int n = a.length;
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
sortcount++;
if (a[j] < a[min]) {
min = j;
}
}
int temp = a[min];
a[min] = a[i];
a[i] = temp;
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of element: ");
int n = s.nextInt();
int[] a = new int[n];
//use random class object to generate random values
Random r = new Random();
System.out.println("intput numbers");
for (int i = 0; i < n; i++) {
a[i] = r.nextInt(10000); // Random numbers between 0 and
9999
System.out.println(a[i] + " ");
}
selSort(a);
System.out.println("Sorted numbers are:");
for(int i=0;i<n;i++)
System.out.println(a[i]);
System.out.println("Number of basic operations for sorting is:
"+sortcount);
}
}
Output:
Enter the number of element:
5
intput numbers
5275
3209
802
6226
5501
Sorted numbers are:
802
3209
5275
5501
6226
Number of basic operations for sorting is: 10