使用泛型实现对int数组或者String数组进行排序

版权声明:作者: Daley Zou ( https://blog.csdn.net/DaleyZou ) 出处: https://blog.csdn.net/DaleyZou/article/details/83513780

因为是使用的泛型,我们并不确定数据类型,
对于数据的比较就不能用平时的大于或者小于。
我们需要比较对象实现Comparable接口,该接口下的compareTo()方法可以用来比大小

定义Sort类:

package com.daleyzou.blog;

/**
 * @Author: DaleyZou
 * @Description: 定义进行排序都需要哪些方法
 * @Date: Created in 20:57 2018/10/29
 * @Modified By:
 */
public abstract class Sort<T extends Comparable<T>> {
    public abstract void sort(T[] nums); // 排序的方法

    public int less(T v, T w){ // 比较大小
        return v.compareTo(w);
    }

    public void swap(T[] nums, int i, int j){ // 进行数组值交换
        T temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

排序方法使用快速排序:

package com.daleyzou.blog;

import java.util.Arrays;

/**
 * @Author: DaleyZou
 * @Description: 使用泛型实现对int数组或者String数组进行排序
 *                  基于快速排序实现
 * @Date: Created in 21:07 2018/10/29
 * @Modified By:
 */
public class BubbleSort<T extends Comparable<T>> extends Sort<T> {
    @Override
    public void sort(T[] nums) {
        boolean isSorted = false;
        for (int i = 0; i < nums.length; i++){
            isSorted = true;
            for (int j = 1; j < nums.length - i; j++){
                if (nums[j].compareTo(nums[j - 1]) < 0){
                    swap(nums, j, j - 1);
                    isSorted = false;
                }
            }
            if (isSorted){
                break;
            }
        }
    }

    public static void main(String[] args){
        // 验证String类型
        String[] strs = new String[]{"123", "1234", "1"};
        BubbleSort<String> strSort = new BubbleSort<>();
        strSort.sort(strs);
        System.out.println("验证String类型:");
        Arrays.stream(strs).forEach(System.out::println);

        // 验证int类型
        Integer[] ints = new Integer[]{123,1234,1};
        BubbleSort<Integer> intSort = new BubbleSort<>();
        intSort.sort(ints);
        System.out.println("验证int类型");
        Arrays.stream(ints).forEach(System.out::println);
    }
}

猜你喜欢

转载自blog.csdn.net/DaleyZou/article/details/83513780