The Program of Algorithms ------- Sorting in Linear Time---- Bucket Sort

Bucket Sort:

Bucket sort assumes that the input is generated by a random process that distributes elements uniformly and independently over the interval [0,1). That is to say, the input number should between 0 and 1. It can use normalization to process the input numbers.


Idea:

Partition 0 to 1 into n part, each part has the same gap(bucket).

Distribution the input num into the bucket.

Then sort each bucket using comparsion algorithms, such as inserting sort.


Realization using Cpp as follow.

#include 
#include 


using namespace std;


float * preProcess(int *A,int p,int q){
	int size=q-p+1;
	int max=A[p],min=A[p];
	for(int i=p+1;imax){
			max=A[i];
		}
		if(A[i]val=RealArr[p+i];
		one_node->next=NULL;
		int index=(int)(Arr[p+i]*size);
		if(!Table[index]){
			Table[index]=one_node;
		}else{
			Node* pNode=Table[index];
			while(pNode->next!=NULL){
				pNode=pNode->next;
			}
			pNode->next=one_node;
		}
	}

	//Sorting in each bucket
	for(int i=0;inext;
		else
			pNode=NULL;

		while(pFrontNode!=NULL&&pNode!=NULL){
			Node* qFrontNode=NULL;
			Node* qNode=Table[i];
			Node* tmpPNodeNext;
			while(qNode!=pNode){
				if(qNode->val>pNode->val){
					if(qFrontNode!=NULL){
						tmpPNodeNext=pNode->next;
						pFrontNode->next=pNode->next;
						pNode->next=qNode;
						qFrontNode->next=pNode;
						break;
					}else{
						tmpPNodeNext=pNode->next;
						pFrontNode->next=pNode->next;
						pNode->next=qNode;
						Table[i]=pNode;
						break;
					}
				}
				
				if(!qFrontNode){
					qFrontNode=Table[i];
				}else{
					qFrontNode=qFrontNode->next;
				}
				qNode=qNode->next;
			}
			if(qNode!=pNode){
				pNode=tmpPNodeNext;
			}
			else{
				pNode=pNode->next;
				pFrontNode=pFrontNode->next;
			}
		}
	}

	//OutPut
	for(int i=0;ival;
			pNode=pNode->next;
		}
		cout<

While you use the inserting sort, the worst case will be O(n^2). You can substitute with the merge sort or quicket sort to decline the worst case to O(nlgn).



BTW:

From some point, it looks a bit like the hash algorithm which use list to handle the collision.

你可能感兴趣的:(Algorithms)