简体   繁体   中英

How to sort any generic collection using bubble sort and check if it's sorted?

I have to implement a method which sorts any kind of collection by using bubble sort and after that to test if it really is sorted how can I accomplish this by using generics ?

This is what i've done so far :

public class SortManager {
    public <T extends Collection> void bubbleSort(T collection) {
        //sort a given collection

    }

    public <T extends Collection<?>> boolean isSorted(T collection) {
        //need to check if a given collection is sorted
        return false;
    }
}

And the test:

@Test
    public void testIfTheCollectionsAreSorted() {
        ArrayList<Integer> integers = new ArrayList<>();

        SortManager sortManager = new SortManager();
        sortManager.bubbleSort(integers);
        assertTrue(sortManager.isSorted(integers));
    }

You can not sort any given collection, because not all collections are ordered. However, you can sort any List<...>

Bubble sort is easily looked up and implemented, what you missed here is that the elements must implement Comparable<...> or change the signature to take a comparator (but you probably want the latter)

class SortManager {
    public <T> void bubbleSort(List<T> list, Comparator<? super T> comp) {
        ...
    }

    public <T> boolean isSorted(List<T> list, Comparator<? super T> comp) {
        ...
        return false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM