码迷,mamicode.com
首页 > 编程语言 > 详细

Java中数组常见的几种排序方法!

时间:2017-05-23 00:26:35      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:常见   ++   str   .so   copy   sea   class   bsp   search   

  数组的定义:

     int[] arr = new int[5];

        int[] arr1 = {1,2,3,4,5};
        
        long[] arr2 = new long[6];
        
        String[] strs = new String[5];
        
        Person[] ps = new Person[5];

  数组的操作:

     int[] arr = {45, 34, 53, 43};
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
        
        // 二分搜索法(使用之前需要先排序)
        int i = Arrays.binarySearch(arr, 34);
        System.out.println(i);
        int[] newArr = Arrays.copyOf(arr, 7);
        int[] newArr1 = Arrays.copyOfRange(arr, 1, 3);
        System.out.println(Arrays.toString(newArr));
        System.out.println(Arrays.toString(newArr1));
        
        int j = Arrays.binarySearch(arr, 1, 3, 34);
        System.out.println(j);

  冒泡排序:

     int[] arr = {23,12,48,56,45};
     int
temp = -1; for(int i=0;i<arr.length;i++) { for(int j=i+1;j<arr.length;j++) { if(arr[i]>arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } System.out.println(Arrays.toString(arr));

  直接选择排序:

    int[] arr = {23,12,48,56,45};
    for(int i=0;i<arr.length;i++) {
            int tem = i;
            for(int j=i;j<arr.length;j++) {
                if(arr[j] < arr[tem]) {
                    tem = j;
                }
            }
            int temp1 = arr[i];
            arr[i] = arr[tem];
            arr[tem] = temp1;
        }
        System.out.println(Arrays.toString(arr));

  反转排序:  

    int[] arr = {23,12,48,56,45};
    for(int i=0;i<arr.length / 2;i++) {
            int temp = arr[i];
            arr[i] = arr[arr.length-i-1];
            arr[arr.length-i-1] = temp;
        }
        System.out.println(Arrays.toString(arr))

 

Java中数组常见的几种排序方法!

标签:常见   ++   str   .so   copy   sea   class   bsp   search   

原文地址:http://www.cnblogs.com/bekeyuan123/p/6891875.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!