A Developer's Diary

Nov 21, 2012

Selection Sort in Java using Generics

A generic implementation of Selection Sort in Java using Generics

 1 import org.junit.Assert;
 2 import org.junit.Test;
 3 
 4 class GenericSelectionSorter
 5 {
 6     public <T extends Comparable<T>> void sort(T[] elems) {
 7         int size = elems.length;
 8 
 9         for (int outerLoopIdx = 0; outerLoopIdx < size - 1; ++outerLoopIdx) {
10             int min = outerLoopIdx;
11             for (int innerLoopIdx = outerLoopIdx; innerLoopIdx < size; ++innerLoopIdx) {
12                 if (elems[min].compareTo(elems[innerLoopIdx]) > 0) {
13                     min = innerLoopIdx;
14                 }
15             }
16 
17             // exchange elements at outerIndexLoop and min positions
18             T temp = elems[min];
19             elems[min] = elems[outerLoopIdx];
20             elems[outerLoopIdx] = temp;
21         }
22     }
23 }
24 
25 public class SelectionSortTester
26 {
27     private String[] unsortedNames = new String[] {
28             "Pankaj",
29             "Paresh",
30             "Ankit",
31             "Sankalp",
32             "Aditya",
33             "Prem",
34             "Rocket",
35             "Singh",
36             "Alabama",
37             "Alaska",
38             "Animal" };
39 
40     private String[] sortedNames = new String[] {
41             "Aditya",
42             "Alabama",
43             "Alaska",
44             "Animal",
45             "Ankit",
46             "Pankaj",
47             "Paresh",
48             "Prem",
49             "Rocket",
50             "Sankalp",
51             "Singh" };
52 
53     @Test
54     public void testStringSort() {
55         GenericSelectionSorter ss = new GenericSelectionSorter();
56         ss.sort(unsortedNames);
57         Assert.assertArrayEquals(unsortedNames, sortedNames);
58     }
59 }

No comments :

Post a Comment