Nov 22, 2012

Insertion Sort in Java using Generics

A generic implementation of Insertion Sort in Java

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

No comments :

Post a Comment