zoukankan      html  css  js  c++  java
  • Java基础知识强化51:经典排序之桶排序(BucketSort)

    1. 首先说明三点:

    (1)桶排序是稳定的

    (2)桶排序是常见排序里最快的一种比快排还要快…大多数情况下

    (3)桶排序非常快,但是同时也非常耗空间,基本上是最耗空间的一种排序算法

    2. 桶排序的分析过程

    对无序数组有个要求,就是成员隶属于固定(有限的)的区间,如范围为[0-9],考试分数为1-100

    例如待排数字[6,2,4,1,5,9]

    准备10个空桶(桶数是固定区间中最大数,比如这里就是10

    [6 2 4 1 5 9]               待排数组

    [0 0 0 0 0 0 0 0 0 0]   空桶

    [0 1 2 3 4 5 6 7 8 9]   桶编号(实际不存在)

    (1)顺序从待排数组中取出数字,首先6被取出,然后把6入6号桶,这个过程类似这样:空桶[ 待排数组[ 0 ] ] = 待排数组[ 0 ]

    [6 2 4 1 5 9]             待排数组

    [0 0 0 0 0 0 6 0 0 0]   空桶

    [0 1 2 3 4 5 6 7 8 9]   桶编号(实际不存在)

    (2)顺序从待排数组中取出下一个数字,此时2被取出,将其放入2号桶,是几就放几号桶:

    [6 2 4 1 5 9]               待排数组

    [0 0 2 0 0 0 6 0 0 0]   空桶

    [0 1 2 3 4 5 6 7 8 9]   桶编号(实际不存在)

    (3)4,5,6省略,过程一样,全部入桶后变成下边这样:

    [6 2 4 1 5 9]               待排数组

    [0 1 2 4 5 6 0 0 9]   空桶

    [0 1 2 4 5 6 7 8 9]   桶编号(实际不存在)

     

    0表示空桶,跳过,顺序取出即可:1 2 4 5 6 9

    3. 桶排序代码实现:

     1 /* package whatever; // don't place package name! */
     2 
     3 import java.util.*;
     4 import java.lang.*;
     5 import java.io.*;
     6 
     7 /* Name of the class has to be "Main" only if the class is public. */
     8 class Ideone
     9 {
    10     public static void main (String[] args) throws java.lang.Exception
    11     {
    12         int[] Array = { 99, 65, 24, 47, 50, 88,33, 66, 67, 31, 18 };
    13         int[] newArray = bucketSort(Array,99);
    14         printArray(newArray);
    15     }
    16     
    17     public static int[] bucketSort(int[] array,int maxNumber) {
    18         int[] newArray = new int[maxNumber + 1];
    19         
    20         for(int i=0; i<array.length; i++) {
    21             newArray[array[i]] = array[i];
    22             
    23         }
    24         
    25         return newArray;
    26     }
    27     
    28     // 打印功能
    29     public static void printArray(int[] arr) {
    30         System.out.print("[");
    31         for (int x = 0; x < arr.length; x++) {
    32            
    33            if(arr[x] >0) {
    34                    System.out.print(arr[x]+" ");
    35            }
    36         }
    37         System.out.println("]");
    38     }
    39 }

    运行效果,如下:

  • 相关阅读:
    Unity错误-(Android build error) Can not sign application Unable to sign application; please provide passwords!
    C#WCF中传输List对象
    抓包工具Omnipeek,Wireshark
    Ubuntu18+.netcore+Nginx+Supervisor部署ASP.NET项目
    3D成像技术
    3D显示技术
    学习模电与数电
    【Java123】解决PKIX path building failed / unable to find valid certification path to requested target
    【Python123】Introduction
    【WebConsole123】练习案例之浏览器访问服务器shell
  • 原文地址:https://www.cnblogs.com/hebao0514/p/4832191.html
Copyright © 2011-2022 走看看