A Developer's Diary

Nov 21, 2012

Bubble Sort in Java using Generics

Below is a generic implementation of Bubble Sort in Java

 1 import org.junit.Assert;
 2 import org.junit.Test;
 3 
 4 class GenericBubbleSorter<T extends Comparable<T>>
 5 {
 6     public void sort(T[] elems) {
 7         int size = elems.length;
 8 
 9         for (int outerLoopIdx = 0; outerLoopIdx < size; ++outerLoopIdx) {
10             for (int innerLoopIdx = 0; innerLoopIdx < (size - outerLoopIdx - 1); ++innerLoopIdx) {
11                 if (elems[innerLoopIdx].compareTo(elems[innerLoopIdx + 1]) > 0) {
12                     T temp = elems[innerLoopIdx];
13                     elems[innerLoopIdx] = elems[innerLoopIdx + 1];
14                     elems[innerLoopIdx + 1] = temp;
15                 }
16             }
17         }
18     }
19 }
20 
21 public class BubbleSortTester
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         GenericBubbleSorter<String> bs = new GenericBubbleSorter<String>();
52         bs.sort(unsortedNames);
53         Assert.assertArrayEquals(unsortedNames, sortedNames);
54     }
55 }

No comments :

Post a Comment