各种排序算法的分析及java&python实现

电子说

1.2w人已加入

描述

排序大的分类可以分为两种:内排序和外排序。在排序过程中,全部记录存放在内存,则称为内排序,如果排序过程中需要使用外存,则称为外排序。下面讲的排序都是属于内排序。

内排序有可以分为以下几类:(1)、插入排序:直接插入排序、二分法插入排序、希尔排序。(2)、选择排序:简单选择排序、堆排序。(3)、交换排序:冒泡排序、快速排序。(4)、归并排序(5)、基数排序

插入排序

思想

每步将一个待排序的记录,按其顺序码大小插入到前面已经排序的字序列的合适位置,直到全部插入排序完为止。

1.1 直接插入排序

基本思想

每步将一个待排序的记录,按其顺序码大小插入到前面已经排序的字序列的合适位置(从后向前找到合适位置后),直到全部插入排序完为止。

图示

JAVA

Java代码实现

package sort;public class StraightInsertionSort {    public static void main(String[] args){        int[] arr = {49,38,65,97,76,13,27,49,78,34,12,64,1};System.out.println("排序之前:");printArray(arr);        for(int i = 0;i < arr.length;i++){            int temp = arr[i];            int j;            for(j=i-1;j>=0;j--){                    if(arr[j] > temp)            arr[j+1] = arr[j];                    else            break;    }    arr[j+1] = temp;}System.out.println(" ");System.out.println("排序之后:");printArray(arr);}    private static void printArray(int[] arr){        for(int x:arr){    System.out.print(x + " ");    }  }}

Python代码实现

def insertion_sort(a_list):for index in range(1,len(a_list)):current_value = a_list[index]        #这里不能减1position = index        # 这里比较的是前一个位置的值while position > 0 and a_list[position - 1]> current_value:    a_list[position] = a_list[position - 1]    position -= 1a_list[position] = current_valuea_list = [54, 26, 93, 15, 77, 31, 44, 55, 20]print(a_list)insertion_sort(a_list)print(a_list)

算法分析

直接插入排序是稳定的排序。直接插入排序的平均时间复杂度为O(n^2)。

文件初态不同时,直接插入排序所耗费的时间有很大差异。若文件初态为正序,则每个待插入的记录只需要比较一次就能够找到合适的位置插入,故算法的时间复杂度为O(n),这时最好的情况。若初态为反序,则第i个待插入记录需要比较i+1次才能找到合适位置插入,故时间复杂度为O(n^2),这时最坏的情况。

1.2 二分法插入排序

基本思想二分法插入排序的思想和直接插入一样,只是找合适的插入位置的方式不同,这里是按二分法找到合适的位置,可以减少比较的次数。

图示

JAVA

Java代码实现

 package sort;public class insertionSortBinarysearch {     public static void main(String[] args){        int[] arr = {49,38,65,97,76,13,27,49,78,34,12,64,1};System.out.println("排序之前:");printArray(arr);sort(arr);System.out.println(" ");System.out.println("排序之后:");printArray(arr);}    private static void sort(int[] arr){        for(int i = 1;i < arr.length;i++){                int temp = arr[i];                int left = 0;                int right = i - 1;                int mid;                while(left <= right){        mid = (right - left) / 2 + left;                        if (arr[mid] > temp)            right = mid - 1;                        else            left = mid + 1;    }                for(int j=i-1;j>=left;j--){        arr[j+1] = arr[j];    }    arr[left] = temp;   }}    private static void printArray(int[] arr){        for(int x:arr){    System.out.print(x + " ");    }  }}

Python代码实现

def insertion_sort_binarysearch(a_list):for index in range(1,len(a_list)):low = 0high = index - 1current_value = a_list[index]position = index       while low<=high:   middle = (low+high)//2   if a_list[middle] > current_value:       high = middle -1   else:       low = middle + 1while position > low:   a_list[position] = a_list[position - 1]   position -= 1a_list[low] = current_valuea_list = [54, 26, 93, 15, 77, 31, 44, 55, 20]insertion_sort_binarysearch(a_list)print(a_list)

算法分析

二分法插入排序也是稳定的。

二分插入排序的比较次数与待排序记录的初始状态无关,仅依赖于记录的个数。当n较大时,比直接插入排序的最大比较次数少得多。但大于直接插入排序的最小比较次数。算法的移动次数与直接插入排序算法的相同,最坏的情况为n2/2,最好的情况为n,平均移动次数为O(n2)。

1.3 希尔排序

基本思想

先取一个小于n的整数d1作为第一个增量,把文件的全部记录分成d1个组。所有距离为d1的倍数的记录放在同一个组中。先在各组内进行直接插入排序;然后,取第二个增量d2

图示

JAVA

Java代码实现

 package sort;public class shellSort {     public static void main(String[] args){        int[] arr = {49,38,65,97,76,13,27,49,78,34,12,64,1};System.out.println("排序之前:");printArray(arr);        int d = arr.length;        int temp;        while(d>1){    d /= 2;                for(int i = d;i= 0 && arr[j] > temp){            arr[j+d] = arr[j];            j = j - d;        }        arr[j+d] = temp;    }}System.out.println(" ");System.out.println("排序之后:");printArray(arr);}    private static void printArray(int[] arr){        for(int x:arr){    System.out.print(x + " ");    }  }}

Python代码实现

def shell_sort(a_list):#how many sublists, also how many elements in a sublistsublist_count = len(a_list) // 2while sublist_count > 0:        for start_position in range(sublist_count):gap_insertion_sort(a_list, start_position, sublist_count)print("After increments of size", sublist_count, "The list is", a_list)sublist_count = sublist_count // 2def gap_insertion_sort(a_list, start, gap):#start+gap is the second element in this sublistfor i in range(start + gap, len(a_list), gap):current_value = a_list[I]position = I        while position >= gap and a_list[position - gap] > current_value:    a_list[position] = a_list[position - gap] #move backward    position = position - gap    a_list[position] = current_valuea_list = [54, 26, 93, 17, 77, 31, 44, 55, 20, 88]shell_sort(a_list)print(a_list)

算法分析

我们知道一次插入排序是稳定的,但在不同的插入排序过程中,相同的元素可能在各自的插入排序中移动,最后其稳定性就会被打乱,所以希尔排序是不稳定的。

希尔排序的时间性能优于直接插入排序,原因如下:

(1)当文件初态基本有序时直接插入排序所需的比较和移动次数均较少。

(2)当n值较小时,n和n2的差别也较小,即直接插入排序的最好时间复杂度O(n)和最坏时间复杂度0(n2)差别不大。

(3)在希尔排序开始时增量较大,分组较多,每组的记录数目少,故各组内直接插入较快,后来增量di逐渐缩小,分组数逐渐减少,而各组的记录数目逐渐增多,但由于已经按di-1作为距离排过序,使文件较接近于有序状态,所以新的一趟排序过程也较快。

因此,希尔排序在效率上较直接插人排序有较大的改进。

希尔排序的平均时间复杂度为O(nlogn)。

选择排序

基本思想

每趟从待排序的记录序列中选择关键字最小的记录放置到已排序表的最前位置,直到全部排完。

2.1 直接选择排序

基本思想

在要排序的一组数中,选出最小的一个数与第一个位置的数交换;然后在剩下的数当中再找最小的与第二个位置的数交换,如此循环到倒数第二个数和最后一个数比较为止。

图示

JAVA

Java代码实现

 package sort;public class SelectionSort {     public static void main(String[] args){        int[] arr = {49,38,65,97,76,13,27,49,78,34,12,64,1};System.out.println("排序之前:");printArray(arr);        for(int i = 0;i

Python代码实现

 """选择排序"""def selection_sort(a_list):for fill_slot in range(len(a_list)-1,0,-1):max_index = 0for i in range(1,fill_slot+1):            if a_list[i] > a_list[max_index]:    max_index=Ia_list[max_index],a_list[fill_slot] = a_list[fill_slot],a_list[max_index]if __name__ == '__main__':a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]selection_sort(a_list)print(a_list)

算法分析

简单选择排序是不稳定的排序。

时间复杂度:T(n)=O(n^2)。

2.2 堆排序

基本思想

堆排序是一种树形选择排序,是对直接选择排序的有效改进。

、堆的定义下:具有n个元素的序列 (h1,h2,...,hn),当且仅当满足(hi>=h2i,hi>=2i+1)或(hi<=h2i,hi<=2i+1) (i=1,2,...,n/2)时称之为堆。在这里只讨论满足前者条件的堆。由堆的定义可以看出,堆顶元素(即第一个元素)必为最大项(大顶堆)。完全二 叉树可以很直观地表示堆的结构。堆顶为根,其它为左子树、右子树。

初始时把要排序的数的序列看作是一棵顺序存储的二叉树,调整它们的存储序,使之成为一个 堆,这时堆的根节点的数最大。然后将根节点与堆的最后一个节点交换。然后对前面(n-1)个数重新调整使之成为堆。依此类推,直到只有两个节点的堆,并对 它们作交换,最后得到有n个节点的有序序列。从算法描述来看,堆排序需要两个过程,一是建立堆,二是堆顶与堆的最后一个元素交换位置。所以堆排序有两个函数组成。一是建堆的渗透函数,二是反复调用渗透函数实现排序的函数。

图示

建堆

JAVA

交换,从堆中踢出最大数

JAVA

Java代码实现

 package sort;public class HeapSort {     public static void main(String[] args){        int[] arr = {49,38,65,97,76,13,27,49,78,34,12,64,1};System.out.println("排序之前:");printArray(arr);heapSort(arr);System.out.println(" ");System.out.println("排序之后:");printArray(arr);}    private static void heapSort(int[] arr){        //build heapint N = arr.length;        for(int i=N / 2;i>=0;i--)    perceDown(arr,i,N);        for(int i=N-1;i>=0;i--){                int temp = arr[i];    arr[i] = arr[0];    arr[0] = temp;    perceDown(arr,0,i);   }}    private static void perceDown(int[] arr,int i,int N){        // i:要替换的元素// N:终止的位置int temp = arr[i];        int child = i * 2 + 1;        while(child < N){                if(child + 1 < N && arr[child+1] > arr[child])        child = child + 1;                if(temp < arr[child]){        arr[i] = arr[child];        i = child;    }            else        break;    child = 2 * i + 1;}arr[i] = temp;}    private static void printArray(int[] arr){        for(int x:arr){    System.out.print(x + " ");    }  }}

Python代码实现

def perceDown(a_list,i,N):temp = a_list[I]    while (2*i + 1) < N:child = 2 * i + 1if child < N - 1 and a_list[child+1] > a_list[child]:    child = child + 1if temp < a_list[child]:    a_list[i] = a_list[child]    i = child        else:                 breaka_list[i] = tempdef heap_sort(a_list,N):for i in range(N//2,-1,-1):perceDown(a_list,i,N)    for i in range(N-1,-1,-1):a_list[0],a_list[i] = a_list[i],a_list[0]perceDown(a_list,0,i)if __name__ == '__main__':a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]heap_sort(a_list,9)print(a_list)

算法分析

堆排序也是一种不稳定的排序算法。

堆排序优于简单选择排序的原因:直接选择排序中,为了从R[1..n]中选出关键字最小的记录,必须进行n-1次比较,然后在R[2..n]中选出关键字最小的记录,又需要做n-2次比较。事实上,后面的n-2次比较中,有许多比较可能在前面的n-1次比较中已经做过,但由于前一趟排序时未保留这些比较结果,所以后一趟排序时又重复执行了这些比较操作。

堆排序可通过树形结构保存部分比较结果,可减少比较次数。

堆排序的最坏[时间复杂度为O(nlogn)。堆序的平均性能较接近于最坏性能。由于建初始堆所需的比较次数较多,所以堆排序不适宜于记录数较少的文件。

有关堆排序的知识,可以参照另一篇帖子:https://www.jianshu.com/p/541d166ce6c2

交换排序

3.1 冒泡排序

基本思想

在要排序的一组数中,对当前还未排好序的范围内的全部数,自上而下对相邻的两个数依次进行比较和调整,让较大的数往下沉,较小的往上冒。即:每当两相邻的数比较后发现它们的排序与排序要求相反时,就将它们互换。

图示

JAVA

Java代码实现

 package sort;public class BubbleSort {     public static void main(String[] args){        int[] arr = {49,38,65,97,76,13,27,49,78,34,12,64,1};System.out.println("排序之前:");printArray(arr);        for(int i = 0; i arr[j]){                                int temp = arr[j];            arr[j] = arr[j-1];            arr[j-1] = temp;        }    }System.out.println(" ");System.out.println("排序之后:");printArray(arr);}    private static void printArray(int[] arr){        for(int x:arr){    System.out.print(x + " ");     }   }}

Python代码实现

def short_bubble_sort(a_list):pass_num = len(a_list)-1exchanges = Truewhile pass_num > 0 and exchanges:exchanges = Falsefor i in range(pass_num):                if a_list[i] > a_list[i+1]:        a_list[i],a_list[i+1] = a_list[i+1],a_list[I]        exchanges = Truepass_num -= 1

算法分析

冒泡排序是一种稳定的排序方法。

若文件初状为正序,则一趟起泡就可完成排序,排序码的比较次数为n-1,且没有记录移动,时间复杂度是O(n)

若文件初态为逆序,则需要n-1趟起泡,每趟进行n-i次排序码的比较,且每次比较都移动三次,比较和移动次数均达到最大值∶O(n^2)

起泡排序平均时间复杂度为O(n^2)

3.2 快速排序

基本思想选择一个基准元素,通常选择第一个元素或者最后一个元素,通过一趟扫描,将待排序列分成两部分,一部分比基准元素小,一部分大于等于基准元素,此时基准元素在其排好序后的正确位置,然后再用同样的方法递归地排序划分的两部分。

图示

JAVA

Java代码实现

package sort;public class QuickSort {    public static void main(String[] args){        int[] arr = {49,38,65,97,76,13,27,49,78,34,12,64,1};System.out.println("排序之前:");printArray(arr);quickSort(arr,0,arr.length-1);System.out.println(" ");System.out.println("排序之后:");printArray(arr);}    private static void quickSort(int[] arr,int start,int end){        if(start < end){                int mid = partition(arr,start,end);    quickSort(arr,start,mid-1);    quickSort(arr,mid+1,end);   } }     private static int partition(int[] arr,int start,int end){        int temp = arr[start];        int left = start + 1;        int right = end;        while(left <= right){                while (left <= right && arr[left] <= temp)        left += 1;                while (left <= right && arr[right] >= temp)        right -= 1;                if (left <= right){                        int t = arr[left];        arr[left] = arr[right];        arr[right] = t;    }                else        break;}arr[start] = arr[right];arr[right] = temp;        return right;}    private static void printArray(int[] arr){        for(int x:arr){    System.out.print(x + " ");    }  }}

Python代码实现

def quick_sort(a_list):quick_sort_helper(a_list,0,len(a_list)-1)def quick_sort_helper(a_list,first,last):if first= pivot_value and right_mark >= left_mark:    right_mark -= 1if right_mark < left_mark:    done = Trueelse:    a_list[right_mark],a_list[left_mark] = a_list[left_mark],a_list[right_mark]a_list[first],a_list[right_mark] = a_list[right_mark],a_list[first]    return left_marka_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]quick_sort(a_list)print(a_list)

算法分析

快速排序是不稳定的排序。

快速排序的时间复杂度为O(nlogn)。

当n较大时使用快排比较好,当序列基本有序时用快排反而不好。

归并排序

基本思想归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列。图示

JAVA

Java代码实现

package sort;public class MergeSort {    public static void main(String[] args){        int[] arr = {49,38,65,97,76,13,27,49,78,34,12,64,1};System.out.println("排序之前:");printArray(arr);mergeSort(arr,0,arr.length-1);System.out.println(" ");System.out.println("排序之后:");printArray(arr);}    private static void mergeSort(int[] arr,int start,int end){        if (end - start > 0){                int mid = (end - start) / 2 + start;    mergeSort(arr,start,mid);    mergeSort(arr,mid+1,end);                int[] temp = new int[arr.length];                int tempIndex = start;                int left = start;                int right = mid + 1;                while(left <= mid && right <= end){                //从两个数组中选取较小的数放入中间数组        if(arr[left] <= arr[right])            temp[tempIndex++] = arr[left++];                        else            temp[tempIndex++] = arr[right++];    }            //将剩余的部分放入中间数组    while(left <= mid)        temp[tempIndex++] = arr[left++];                while(right <= end)        temp[tempIndex++] = arr[right++];                //将中间数组复制回原数组    tempIndex = start;                while(tempIndex<=end)        arr[tempIndex] = temp[tempIndex++];  }}    private static void printArray(int[] arr){        for(int x:arr){    System.out.print(x + " ");     }  }}

Python代码实现

def merge_sort(a_list):print("Splitting ", a_list)    if len(a_list) > 1:mid = len(a_list)//2left_half = a_list[:mid]right_half = a_list[mid:]merge_sort(left_half)merge_sort(right_half)I=0j=0k=0while i

算法分析

归并排序是稳定的排序方法。

归并排序的时间复杂度为O(nlogn)。

速度仅次于快速排序,为稳定排序算法,一般用于对总体无序,但是各子项相对有序的数列。

基数排序

基本思想将所有待比较数值(正整数)统一为同样的数位长度,数位较短的数前面补零。然后,从最低位开始,依次进行一次排序。这样从最低位排序一直到最高位排序完成以后,数列就变成一个有序序列。

图示

JAVA

Java代码实现

package com.sort;//不稳定import java.util.Arrays;public class HeapSort {    public static void main(String[] args) {        int[] a={49,38,65,97,76,13,27,49,78,34,12,64};        int arrayLength=a.length;    //循环建堆  for(int i=0;i=0;i--){            //k保存正在判断的节点     int k=i;            //如果当前k节点的子节点存在      while(k*2+1<=lastIndex){                //k节点的左子节点的索引         int biggerIndex=2*k+1;                //如果biggerIndex小于lastIndex,即biggerIndex+1代表的k节点的右子节点存在        if(biggerIndex

Python代码实现

from random import randintdef radix_sort(lis,d):for i in xrange(d):#d轮排序s = [[] for k in xrange(10)]#因为每一位数字都是0~9,故建立10个桶for j in lis:    s[j/(10**i)%10].append(i)li = [a for b in s for a in b]    return li

算法分析

基数排序是稳定的排序算法。

基数排序的时间复杂度为O(d(n+r)),d为位数,r为基数。

整体分析

6.1 稳定性

稳定:冒泡排序、插入排序、归并排序和基数排序

不稳定:选择排序、快速排序、希尔排序、堆排序

6.2 平均时间复杂度

O(n^2):直接插入排序,简单选择排序,冒泡排序。

在数据规模较小时(9W内),直接插入排序,简单选择排序差不多。当数据较大时,冒泡排序算法的时间代价最高。性能为O(n^2)的算法基本上是相邻元素进行比较,基本上都是稳定的。

O(nlogn):快速排序,归并排序,希尔排序,堆排序。

其中,快排是最好的, 其次是归并和希尔,堆排序在数据量很大时效果明显。

6.3 排序算法的选择

1.数据规模较小

(1)待排序列基本序的情况下,可以选择直接插入排序;(2)对稳定性不作要求宜用简单选择排序,对稳定性有要求宜用插入或冒泡

2.数据规模不是很大

(1)完全可以用内存空间,序列杂乱无序,对稳定性没有要求,快速排序,此时要付出log(N)的额外空间。(2)序列本身可能有序,对稳定性有要求,空间允许下,宜用归并排序

3.数据规模很大

(1)对稳定性有求,则可考虑归并排序。(2)对稳定性没要求,宜用堆排序

4.序列初始基本有序(正序),宜用直接插入,冒泡

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分