Mã:
class Test<U> {
// As we are comparing the Non-primitive data types
// we need to use Comparable class
static <U extends Comparable<U>> void sapXep(U[] arr) {
int i, j, min;
// Selection Sort
for (i = 0; i < arr.length - 1; i++) {
min = i;
for (j = i + 1; j < arr.length; j++) {
if (arr[j].compareTo(arr[min]) < 0) {
min = j;
}
}
swap(i, min, arr);
}
// Printing the elements after sorted
for (U u : arr) {
System.out.print(u + " ");
}
}
static <U> void swap(int a, int b, U[] arr) {
U temp = arr[b];
arr[b] = arr[a];
arr[a] = temp;
}
}
public class Solution {
public static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws Exception {
Integer[] a = { 100, 22, 58, 41, 6, 50 };
Character[] c = { 'v', 'g', 'a', 'c', 'x', 'd', 't' };
String[] s = { "Virat", "Rohit", "Abhinay", "Chandu", "Sam", "Bharat", "Kalam" };
System.out.println("Sorted Integer array : ");
Test.sapXep(a);
System.out.println("\n\n");
System.out.println("Sorted Character array : ");
Test.sapXep(c);
System.out.println("\n\n");
System.out.println("Sorted String array : ");
Test.sapXep(s);
}
}
Output:
Sorted Integer array :
6 22 41 50 58 100
Sorted Character array :
a c d g t v x
Sorted String array :
Abhinay Bharat Chandu Kalam Rohit Sam Virat