8 bucket sort

Non-comparative sorting:

         Comparison sorting is based on comparison between input elements. Any comparison sorting algorithm needs to compare at least nlogn in the worst case. Therefore, quick sort, heap sort, and merge sort are all progressively optimal sorting algorithms. Their worst-case time complexity is O(nlogn).

         Non-comparative sorting is not based on comparison between elements. Including: bucket sorting, base sorting, counting sorting.

 

Bucket sorting:

It belongs to non-in-situ sorting.

 

(1) Ideas:

Assumption: The input is a uniformly distributed real number on the interval [0, 1) generated by a random process. Divide the interval [0, 1) into n subintervals (buckets) of equal size, each bucket size 1/n: [0, 1/n), [1/n, 2/n), [2/n, 3/n),...,[k/n, (k+1)/n ),... Assign n input elements to these buckets, sort the elements in the buckets, and then connect the buckets in sequence to input 0 ≤A[1 ..n] <1 Auxiliary array B[0..n-1] is an array of pointers to buckets.

The sorting process is shown in the figure:

 

(2) Complexity analysis:

(2.1) Time complexity:   

         n: the number of array elements, m: the number of buckets.

         The average time complexity of bucket sorting is linear O(n+c), where c=n*(logn-logm). If relative to the same n, the greater the number of buckets m, the higher the efficiency, and the best time complexity reaches O(n).

         Best case: O(n).

         Average situation: O(n+c).

(2.2) Space complexity:

         The space complexity of bucket sorting is O(n+m). If the input data is very large and the number of buckets is also very large, the space cost is undoubtedly expensive.

 

(3) Stability:

         Bucket sorting is stable.

 

code segment:

#include <stdio.h>    
#define SIZE 16
#define MAXNUM 100		//桶个数最大值  
        
void bucket_sort(int arr[],int len,int max); 
        
int main()    
{    
    int a[SIZE]={2,5,6,12,4,8,8,6,7,8,8,10,7,6,0,1};
    bucket_sort(a,SIZE,12);		//12-->元素最大值
    return 0;
}    

//bucket_sort():桶排序
/*
@param:
arr:待排序数组
len:待排序数组长度
max:待排序数组元素最大值,数组中的元素都落在[0,max]区间
@ret:无
*/
void bucket_sort(int arr[],int len,int max)
{
	int count[MAXNUM];			//空间复杂度O(m)
	for(int i=0;i<=max;i++)
	{
		count[i]=0;
	}

	//遍历待排序数组
	for(int i=0;i<len;i++)
	{
		count[arr[i]]++;
	}
	int k=0;
	printf("排序后: \n");		//桶排序输出
	//数组元素范围[0,max]
	for(int i=0;i<=max;i++)		//时间复杂度O(n+m),外循环m次,内循环共n次	
	{
		for(int j=1;j<=count[i];j++)
		{
			printf("%d ",i);
			arr[k++]=i;			//简化的可以原址排序
		}
	}
	printf("\n");
}

 

Guess you like

Origin blog.csdn.net/u012906122/article/details/103602229