Ten classic algorithmic descriptions and code sorting algorithm implementation

   这里详细讲解了十大经典算法的分类,例如交换排序、插入排序、选择排序等比较类排序,以及计数排序、桶排序和基数排序的非比较类排序,分析了各种排序算法的复杂度和稳定性,还有JAVA代码的详细实现。对冒泡排序、插入排序、选择排序和堆排序等十种算法进行了详细的思想总结。

First, an overview of the algorithm

1, classification algorithm

10 common sorting algorithm can be divided into two categories:
(1) comparing the class sorting: to determine the relative order between the elements by comparing, since it can not break through time complexity O (nlogn) thus also called nonlinear time comparison based sorting .
(2) Comparison of the non-sort categories: comparison between the relative order of elements does not pass through, it can break through the lower bound based on the comparison time ordered, run in linear time, also known as non-linear time-based ordering comparison.

Ten classic algorithmic descriptions and code sorting algorithm implementation

2, algorithm complexity

Ten classic algorithmic descriptions and code sorting algorithm implementation

3, related concepts

(1) stable

a front still after if a b originally in front of b, and a = b, sort.

(2) unstable

B if a is in front of the original, and a = b, then a sorting may occur at the back of b.

(3) time complexity

The total number of operations to sort the data. When n changes reflect what law the number of operations presented.

(4) the spatial complexity

Refers to the time required storage space metric algorithm is executed in a computer, it is also a function of the data size n.

Second, the code sorting algorithm implementation

1, bubble sort (Bubble Sort)

   冒泡排序是一种简单的排序算法。它重复地走访过要排序的数列,一次比较两个元素,如果它们的顺序错误就把它们交换过来。走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。

1.1 Algorithm Description

(1) comparing adjacent elements. If the first than the second large, two are exchanged;
(2) to do the same work for each pair of adjacent elements, from the beginning to the end of the last of the first pair so that the last element should is the largest number;
(3) a step for repeating the above all elements, except the last one;
(4) repeating steps 1 to 3 until the sorting is completed.

1.2, code implementation

General implementation (1) java code

   // 一般的冒泡排序
    public static void BubbleSort(int[] arr){
        int temp; //临时变量
        for (int i = arr.length-1;i > 0 ; i--){ // 表示趟数,一共arr.length-1次
            for (int j = 0;j < i; j++){  // 表示比较次数,从后往前,每趟比较把最大的冒到最后面
                System.out.println("第"+(arr.length-i)+"趟"+ "第"+(j+1)+"次比较"+Arrays.toString(arr));
                if(arr[j] > arr[j+1]){
                    temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
    }

(2) optimization of the sorting algorithm

   针对问题:数据的顺序排好之后,冒泡算法仍然会继续进行下一轮的比较,直到arr.length-1次,后面的比较没有意义的。
   改进方案:设置标志位flag,如果发生了交换flag设置为true;如果没有交换就设置为false。这样当一轮比较结束后如果flag仍为false,即:这一轮没有发生交换,说明数据的顺序已经排好,没有必要继续进行下去。
public static void BubbleSort(int[] arr){
        int temp; //临时变量
        boolean flag; //是否交换的标记
        for (int i = arr.length-1;i > 0 ; i--){ // 表示趟数,一共arr.length-1次
            flag = false; //设置起始标志位为false
            for (int j = 0;j < i; j++){  // 表示比较次数,从后往前,每趟比较把最大的冒到最后面
                System.out.println("第"+(arr.length-i)+"趟"+ "第"+(j+1)+"次比较"+Arrays.toString(arr));
                if(arr[j] > arr[j+1]){
                    temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                    flag = true;
                }
            }
            if (!flag) break;
        }
}

(3) improved bubble sort Cocktail

   改进的冒泡排序,鸡尾酒冒泡排序,也叫定向冒泡排序,它的改进在于同时的冒泡两边,从低到高,然后从高到低,相当于顺便把最小的数也冒泡到最前面。
public static void cocktailSort(int[] arr){
        int left = 0,right = arr.length -1,temp;
        while (left < right){
            for (int i = left;i < right;i++){  //将最大值冒到数组末尾
                if (arr[i] > arr[i+1]){
                    temp = arr[i];
                    arr[i] = arr[i+1];
                    arr[i+1] = temp;
                }
            }
            right--;
            for (int i = right;i > left;i--){ //将较小值冒到数组前面
                if (arr[i] < arr[i-1]){
                    temp = arr[i];
                    arr[i] = arr[i-1];
                    arr[i-1] = temp;
                }
            }
            left++;
        }
}

2, selection sort (SelctionSort)

   选择排序(Selection-sort)是一种简单直观的排序算法。它的工作原理:首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。

2.1 Algorithm Description

   n个记录的直接选择排序可经过n-1趟直接选择排序得到有序结果。具体算法描述如下:

(1)初始状态:无序区为R[1..n],有序区为空;
(2)第i趟排序(i=1,2,3…n-1)开始时,当前有序区和无序区分别为R[1..i-1]和R(i..n)。该趟排序从当前无序区中-选出关键字最小的记录 R[k],将它与无序区的第1个记录R交换,使R[1..i]和R[i+1..n)分别变为记录个数增加1个的新有序区和记录个数减少1个的新无序区;
(3)n-1趟结束,数组有序化了。

2.2、代码实现

public static void selectSort(int[] arr){
        //从无序的数组中选出最小值,替换到数组最前面
        for(int i = 0;i < arr.length - 1;i++){
            int minIndex = i;
            for(int j = i + 1;j < arr.length;j++){
                if (arr[minIndex] > arr[j]){
                    minIndex = j;
                }
            }
            int temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
            System.out.println("第"+(i+1)+"次选择"+Arrays.toString(arr));
        }
}

2.3、算法分析

   表现最稳定的排序算法之一,因为无论什么数据进去都是O(n2)的时间复杂度,所以用到它的时候,数据规模越小越好。唯一的好处可能就是不占用额外的内存空间了吧。理论上讲,选择排序可能也是平时排序一般人想到的最多的排序方法了吧。

3、插入排序(Insertion Sort)

    插入排序(Insertion-Sort)的算法描述是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。

3.1算法描述

一般来说,插入排序都采用in-place在数组上实现。具体算法描述如下:
(1)从第一个元素开始,该元素可以认为已经被排序;
(2)取出下一个元素,在已经排序的元素序列中从后向前扫描;
(3)如果该元素(已排序)大于新元素,将该元素移到下一位置;
(4)重复步骤3,直到找到已排序的元素小于或者等于新元素的位置;
(5)将新元素插入到该位置后;
(6)重复步骤2~5。

3.2、代码实现

public static void insetSort(int[] arr){
        for (int i = 0;i < arr.length;i++){
            for (int j = i;j > 0;j--){
                //配合交换的实现
                if (arr[j] < arr[j-1]){
                    int temp = arr[j];
                    arr[j] = arr[j-1];
                    arr[j-1] = temp;
                }else {
                    break;
                }
            }
            System.out.println("第"+(i+1)+"次插入"+Arrays.toString(arr));
        }
}

3.3、算法分析

    插入排序在实现上,通常采用in-place排序(即只需用到O(1)的额外空间的排序),因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。

4、希尔排序(Shell Sort)

   第一个突破O(n2)的排序算法,是简单插入排序的改进版。它与插入排序的不同之处在于,它会优先比较距离较远的元素。希尔排序又叫缩小增量排序。

4.1、算法描述

   先将整个待排序的记录序列分割成为若干子序列分别进行直接插入排序,具体算法描述:

(1)选择一个增量序列t1,t2,…,tk,其中ti>tj,tk=1;
(2)按增量序列个数k,对序列进行k 趟排序;
(3)每趟排序,根据对应的增量ti,将待排序列分割成若干长度为m 的子序列,分别对各子表进行直接插入排序。仅增量因子为1 时,整个序列作为一个表来处理,表长度即为整个序列的长度。

4.2、代码实现

public static void ShellSort(int[] arr){
        //定义增量序列,数组长度的每次折半
        int incre = arr.length;
        int n = 0;
        while (true){
            n += 1;
            incre = incre / 2;
            System.out.println("第"+n+"遍排序,增量序列为:"+incre+Arrays.toString(arr));
            // 根据增量拆分成不同的数组序列,拆分为incre组
            for (int k = 0;k < incre; k++){   //对拆分的序列用插入排序
                for (int i = k;i < arr.length;i += incre){
                    for (int j = i;j>k;j-=incre){
                        if (arr[j] < arr[j-incre]){
                            int temp = arr[j];
                            arr[j] = arr[j-incre];
                            arr[j-incre] = temp;
                        }else {
                            break;
                        }
                    }
                }
            }
            if (incre == 1){
                break;
            }
        }
}

4.3、算法分析

   希尔排序的核心在于间隔序列的设定。既可以提前设定好间隔序列,也可以动态的定义间隔序列。动态定义间隔序列的算法是《算法(第4版)》的合著者Robert Sedgewick提出的。

5、归并排序(Merge Sort)

   归并排序是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为2-路归并。

5.1、算法描述

(1)把长度为n的输入序列分成两个长度为n/2的子序列;
(2)对这两个子序列分别采用归并排序;
(3)将两个排序好的子序列合并成一个最终的排序序列。

5.2、代码实现

public static int[] MergeSort(int[] arr){
        if (arr.length < 2) return arr;
        int mid = arr.length / 2;
        int[] left = Arrays.copyOfRange(arr,0,mid);
        int[] right = Arrays.copyOfRange(arr,mid,arr.length);
        return merge_sort(MergeSort(left),MergeSort(right));
    }

    public static int[] merge_sort(int[] left,int[] right){
        int[] newarr = new int[left.length + right.length];
        for (int index = 0,i = 0,j = 0;index < newarr.length;index++){
            if (i >= left.length){
                newarr[index] = right[j++];
            }else if (j >= right.length){
                newarr[index] = left[i++];
            }else if (left[i] > right[j]){
                newarr[index] = right[j++];
            }else {
                newarr[index] = left[i++];
            }
        }
        return newarr;
}

5.3、算法分析

   归并排序是一种稳定的排序方法。和选择排序一样,归并排序的性能不受输入数据的影响,但表现比选择排序好的多,因为始终都是O(nlogn)的时间复杂度。代价是需要额外的内存空间。

6、快速排序(Quick Sort)

         快速排序的基本思想:通过一趟排序将待排记录分隔成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序。

6.1、算法描述

快速排序使用分治法来把一个串(list)分为两个子串(sub-lists)。具体算法描述如下:
(1)从数列中挑出一个元素,称为 “基准”(pivot);
(2)重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。在这个分区退出之后,该基准就处于数列的中间位置。这个称为分区(partition)操作;
(3)递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序。

6.2、代码实现

public static void QuickSort(int[] arr,int left,int right){
        if (left >= right){
            return;
        }
        //选择第一个数为key
        int l = left,r = right;
        int key = arr[left];

        while (l < r){
            //先从右边找到第一个小于key的数
            while (l < r && key <= arr[r]){
                r--;
            }
            if (l < r){
                arr[l] = arr[r];
                l++;
            }

            //再从左边起找到第一个大于key的值
            while (l < r && key > arr[l]){
                l++;
            }
            if (l<r){
                arr[r] = arr[l];
                r--;
            }
            arr[l] = key;
            QuickSort(arr,left,l-1);
            QuickSort(arr,l+1,right);
        }

    }

    public static void QuickSortFunc(int[] arr){
        int left = 0;
        int right = arr.length-1;
        QuickSort(arr,left,right);
}

7、堆排序(Heap Sort)

   堆排序(Heapsort)是指利用堆这种数据结构所设计的一种排序算法。堆积是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点。

7.1、算法描述

(1)将初始待排序关键字序列(R1,R2….Rn)构建成大顶堆,此堆为初始的无序区;
(2)将堆顶元素R[1]与最后一个元素R[n]交换,此时得到新的无序区(R1,R2,……Rn-1)和新的有序区(Rn),且满足R[1,2…n-1]<=R[n];
(3)由于交换后新的堆顶R[1]可能违反堆的性质,因此需要对当前无序区(R1,R2,……Rn-1)调整为新堆,然后再次将R[1]与无序区最后一个元素交换,得到新的无序区(R1,R2….Rn-2)和新的有序区(Rn-1,Rn)。不断重复此过程直到有序区的元素个数为n-1,则整个排序过程完成。

7.2、代码实现

public static void HeapSort(int[] arr){
        //1、构建大项堆
        for (int i = arr.length/2 - 1;i>=0;i--){
            //从第一个非叶子节点从下至上,从右至左调整结构
            adjustHeap(arr,i,arr.length);
        }

        //2、调整堆结构+交换堆顶元素与末尾元素
        for(int j = arr.length-1;j>0;j--){
            int temp = arr[0];
            arr[0] = arr[j];
            arr[j] = temp;  //将堆顶元素与末尾元素进行交换
            adjustHeap(arr,0,j); //重新进行堆调整
        }
    }

    //调整堆
    public static void adjustHeap(int[] arr,int i,int length){
        //先取出当前元素i
        int temp = arr[i];
        //从i结点的左子结点开始,也就是2i+1处开始
        for (int k = i*2 + 1;k<length;k=k*2+1){
            //如果左子节点小于右子节点,k指向右子节点
            if(k+1<length && arr[k] < arr[k+1]){
                k++;
            }
            if (arr[k] > temp){//如果子节点大于父节点,将子节点值付给父节点(不用进行交换)
                arr[i] = arr[k];
                i = k;
            }else {
                break;
            }
        }
        arr[i] = temp; //将temp值放到最终的位置
}

8、计数排序(Counting Sort)

   计数排序不是基于比较的排序算法,其核心在于将输入的数据值转化为键存储在额外开辟的数组空间中。 作为一种线性时间复杂度的排序,计数排序要求输入的数据必须是有确定范围的整数。
   它的优势在于在对于较小范围内的整数排序。它的复杂度为Ο(n+k)(其中k是待排序数的范围),快于任何比较排序算法,缺点就是非常消耗空间。很明显,如果而且当O(k)>O(n*log(n))的时候其效率反而不如基于比较的排序,比如堆排序和归并排序和快速排序。
   要求:待排序数中最大数值不能太大。

8.1、算法描述

(1)找出待排序的数组中最大和最小的元素;
(2)统计数组中每个值为i的元素出现的次数,存入数组C的第i项;
(3)对所有的计数累加(从C中的第一个元素开始,每一项和前一项相加);
(4)反向填充目标数组:将每个元素i放在新数组的第C(i)项,每放一个元素就将C(i)减去1。

8.2、代码实现

public static int[] CountSort(int[] arr){
        //1、找出数组arr中的最大值
        int k = arr[0];
        for (int i = 1;i < arr.length;i++){
            if (k < arr[i]){
                k = arr[i];
            }

        }

        //2、构造C数组,将A中每个元素对应C中的元素大小+1
        int[] C = new int[k+1];
        int sum = 0;
        for (int i = 0;i < arr.length;i++){
            C[arr[i]] +=1;  //统计A中各元素个数,对应到C数组
         }

        //3、将C中每个i位置的元素大小改成C数组前i项和
        for (int i=0;i<k+1; i++){
            sum += C[i];
            C[i] = sum;
        }

        //4、构造B数组,初始化一个和A同样大小的数组B用于存储排序后数组,然后倒序遍历A中元素(后面会提到为何要倒序遍历),通过查找C数组,将该元素放置到B中相应的位置,同时将C中对应的元素大小-1(表明已经放置了一个这样大小的元素,下次再放同样大小的元素,就要往前挤一个位置)
        int[] B = new int[arr.length];

        for (int i = arr.length-1;i>=0;i--){ //倒序遍历A数组,构造B数组
            B[C[arr[i]]-1] = arr[i]; //将A中该元素放到排序后数组B中指定的位置
            C[arr[i]]--; //将C中该元素-1,方便存放下一个同样大小的元素
        }

        //5、将排序好的数组B返回,完成排序
        return B;
}

8.3、算法分析

   计数排序是一个稳定的排序算法。当输入的元素是 n 个 0到 k 之间的整数时,时间复杂度是O(n+k),空间复杂度也是O(n+k),其排序速度快于任何比较排序算法。当k不是很大并且序列比较集中时,计数排序是一个很有效的排序算法。

9、桶排序

   桶排序是计数排序的升级版。它利用了函数的映射关系,高效与否的关键就在于这个映射函数的确定。桶排序 (Bucket sort)的工作的原理:假设输入数据服从均匀分布,将数据分到有限数量的桶里,每个桶再分别排序(有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排)。
   要求:待排序数长度一致。

9.1、算法描述

(1)设置一个定量的数组当作空桶;
(2)遍历输入数据,并且把数据一个一个放到对应的桶里去;
(3)对每个不是空的桶进行排序;
(4)从不是空的桶里把排好序的数据拼接起来。

9.2、代码实现

算法实现逻辑
(1)找出待排序数组中的最大值max、最小值min
(2)我们使用 动态数组ArrayList 作为桶,桶里放的元素也用 ArrayList 存储。桶的数量为(max-min)/arr.length+1
(3)遍历数组 arr,计算每个元素 arr[i] 放的桶
(4)每个桶各自排序
(5)遍历桶数组,把排序好的元素放进输出数组

public static void BucketSort(int[] arr){
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        for (int i = 0;i < arr.length;i++){
            max = Math.max(max,arr[i]);
            min = Math.min(min,arr[i]);
        }

        //计算桶数
        int bucketNum = (max - min) / arr.length + 1;
        ArrayList<ArrayList<Integer>> bunketArr = new ArrayList<>(bucketNum);
        for (int i = 0;i < bucketNum;i++){
            bunketArr.add(new ArrayList<Integer>());
        }

        for (int i = 0;i<arr.length;i++){
            int num = (arr[i] - min) / (arr.length);
            bunketArr.get(num).add(arr[i]);
        }

        //对每个桶进行排序
        for (int i = 0;i < bunketArr.size();i++){
            Collections.sort(bunketArr.get(i));
        }

        //将桶中排好序的数据依次复制回原数组
        int index = 0;
        for (int i = 0;i < bucketNum;i++){
            for (int j = 0;j < bunketArr.get(i).size();j++){
                arr[index++] = bunketArr.get(i).get(j);
            }
        }
}

9.3、算法分析

   桶排序最好情况下使用线性时间O(n),桶排序的时间复杂度,取决与对各个桶之间数据进行排序的时间复杂度,因为其它部分的时间复杂度都为O(n)。很显然,桶划分的越小,各个桶之间的数据越少,排序所用的时间也会越少。但相应的空间消耗就会增大。

10、基数排序(Radix Sort)

   基数排序是按照低位先排序,然后收集;再按照高位排序,然后再收集;依次类推,直到最高位。有时候有些属性是有优先级顺序的,先按低优先级排序,再按高优先级排序。最后的次序就是高优先级高的在前,高优先级相同的低优先级高的在前。
   基数排序属于“分配式排序”(distribution sort),是非比较类线性时间排序的一种,又称“桶子法”(bucket sort),顾名思义,它是透过键值的部分信息,将要排序的元素分配至某些“桶”中,藉以达到排序的作用。

10.1、算法描述

   基数排序(以×××为例),将×××10进制按每位拆分,然后从低位到高位依次比较各个位。主要分为两个过程:

(1) assigned, start bit begins, according to the bit value (0-9) 0 ~ 9, respectively, into the tub (64 for example, 4 bits, into the tub 4);
(2) collecting and then placed in the bucket numbers 0-9 sequentially into an array of data; and
(3) repeating (1) (2) process, from one to the highest bit (32-bit unsigned integer, such as the maximum number 4294967296, the highest level for the first 10). Radix sort methods can be used LSD (Least Significant Digital) or MSD (Most Significant Digital), LSD are sorted starting from the rightmost key, and MSD on the contrary, starting from the leftmost keys.

10.2, code implementation

public static int[] RadixSort(int[] array) {
        if (array == null || array.length < 2)
            return array;
        // 1.先算出最大数的位数;
        int max = array[0];
        for (int i = 1; i < array.length; i++) {
            max = Math.max(max, array[i]);
        }
        int maxDigit = 0;
        while (max != 0) {
            max /= 10;
            maxDigit++;
        }
        int mod = 10, div = 1;
        ArrayList<ArrayList<Integer>> bucketList = new
                ArrayList<ArrayList<Integer>>();
        for (int i = 0; i < 10; i++)
            bucketList.add(new ArrayList<Integer>());
        for (int i = 0; i < maxDigit; i++, mod *= 10, div *= 10) {
            for (int j = 0; j < array.length; j++) {
                int num = (array[j] % mod) / div;
                bucketList.get(num).add(array[j]);
            }
            int index = 0;
            for (int j = 0; j < bucketList.size(); j++) {
                for (int k = 0; k < bucketList.get(j).size(); k++)
                    array[index++] = bucketList.get(j).get(k);
                bucketList.get(j).clear();
            }
        }
        return array;
    }

10.3, algorithm analysis

   基数排序基于分别排序,分别收集,所以是稳定的。但基数排序的性能比桶排序要略差,每一次关键字的桶分配都需要O(n)的时间复杂度,而且分配之后得到新的关键字序列又需要O(n)的时间复杂度。假如待排数据可以分为d个关键字,则基数排序的时间复杂度将是O(d*2n) ,当然d要远远小于n,因此基本上还是线性级别的。
   基数排序的空间复杂度为O(n+k),其中k为桶的数量。一般来说n>>k,因此额外空间需要大概n个左右。

Guess you like

Origin blog.51cto.com/12824426/2404453