Java数组排序的实现

文章目录

    • 自然升序排序
    • 自然降序排序
    • 数组倒置
    • 随机排序

自然升序排序

使用Arrays类:其中的sort()使用的是“经过调优的快速排序法”

String[] data = {"1", "4", "3", "2"};
System.out.println(Arrays.toString(data)); // [1, 4, 3, 2]
Arrays.sort(data);
System.out.println(Arrays.toString(data)); // [1, 2, 3, 4]

自然降序排序

Arrays.sort(T[] array, Comparator comparator)

使用自定义比较器,对数组元素进行排序(串行排序)

String[] data = {"1", "4", "3", "2"};
System.out.println(Arrays.toString(data)); // [1, 4, 3, 2]
// 实现降序排序,返回-1放左边,1放右边,0保持不变
Arrays.sort(data, (str1, str2) -> {
    if (str1.compareTo(str2) > 0) {
        return -1;
    } else {
        return 1;
    }
});
System.out.println(Arrays.toString(data)); // [4, 3, 2, 1]

数组倒置

  • 直接数组元素对换
public void testReverseSelf() throws Exception {
    System.out.println("use ReverseSelf");

    String[] strings = { "ramer", "jelly", "bean", "cake" };
    System.out.println("\t" + Arrays.toString(strings));
    for (int start = 0, end = strings.length - 1; start < end; start++, end--) {
        String temp = strings[end];
        strings[end] = strings[start];
        strings[start] = temp;
    }
    System.out.println("\t" + Arrays.toString(strings));
}
  • 使用ArrayList: ArrayList存入和取出的顺序是一样的,可以利用这里特性暂时存储数组元素.
public void testArrayList() throws Exception {
    System.out.println("use ArrayList method");

    String[] strings = { "ramer", "jelly", "bean", "cake" };
    System.out.println("\t" + Arrays.toString(strings));
    List<String> list = new ArrayList<>(strings.length);
    for (int i = strings.length - 1; i >= 0; i--) {
        list.add(strings[i]);
    }
    strings = list.toArray(strings);
    System.out.println("\t" + Arrays.toString(strings));
}
  • 使用Collections和Arrays工具类
public void testCollectionsReverse() throws Exception {
    System.out.println("use Collections.reverse() method");

    String[] strings = { "ramer", "jelly", "bean", "cake" };
    System.out.println("\t" + Arrays.toString(strings));
    // 这种方式仅针对引用类型,对于基本类型如:
    // char[] cs = {'a','b','c','g','d'};
    // 应该定义或转换成对应的引用类型: 
    // Character[] cs = {'a','b','c','g','d'};
    Collections.reverse(Arrays.asList(strings));
    System.out.println("\t" + Arrays.toString(strings));
}
  • 速度测试
@Test
public void testTimeDuration() throws Exception {
    recordTime(ArrayReverse.class,"testCollectionsReverse");
    recordTime(ArrayReverse.class,"testArrayList");
    recordTime(ArrayReverse.class,"testReverseSelf");
}

private static String[] strings = new String[1000000];
{
    for (int i = 0; i < 1000000; i++) {
        strings[i] = String.valueOf(i);
    }
}
/**
 * 记录操作执行总时间.
 *  * @param  the generic type
 * @param clazz the clazz
 * @param methodName the method name
 */
public <T> void recordTime(Class<T> clazz, String methodName) {
    long start = System.currentTimeMillis();
    System.out.println("start: " + start);

    Method[] declaredMethods = clazz.getDeclaredMethods();
    for (Method method : declaredMethods) {
        String name = method.getName();
        if (name.equals(methodName)) {
            try {
                method.invoke(clazz.newInstance());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    long end = System.currentTimeMillis();
    System.out.println("end: " + end);
    System.out.println("duration: " + (end - start) + " ms");
}
  • 结果
使用Collections和Arrays工具类: 12 ms 
使用ArrayList: 7 ms 
直接数组元素对换: 4 ms 
当数据量越来越大时,使用ArrayList的方式会变得很慢. 
直接使用数组元素对换,总是最快完成.

总结: 使用Collections和Arrays工具类反转数组元素更简单,但是在原数组上操作时速度更快,并且占用最少的内存.

随机排序

public static void main(String args[])
    {
        int[] Arr  = {1,2,3,4,5,6,7,8,9};
        Random random = new Random();
        for (int i=0;i<Arr.length;i++ ){
            int p = random.nextInt(i+1);//该方法的作用是生成一个随机的int值,该值介于[0,n)的区间
            int tmp = Arr[i];
            Arr[i]=Arr[p];
            Arr[p]=tmp;
        }

        for (int i:Arr
             ) {
            System.out.println(i+"");
        }
    }


你可能感兴趣的:(Java数组排序的实现)