Sort - Bubble Sort

First, the algorithm thought

Each trip will continue to record pairwise comparisons, press "after the former big small" (or "pre-big small") exchange rules.


Second, the algorithm process

Here Insert Picture Description


Third, to achieve

void BubbleSort(int R[],int n)
{
	int i,j;
	int temp;
	for(i=0;i<n;i++)
	{
		for(j=0;j<n-1-i;j++)
		{
			if(R[j]>R[j+1])
			{
				temp=R[j];
				R[j]=R[j+1];
				R[j+1]=temp;
			}
		}
	}
}

Fourth, the algorithm performance analysis

(1) Time Complexity Analysis

Whatever the case, the outer loop is always executed one by one, the number of cycles for the external n

  • Consider the worst case, i.e. the entire sequence are in reverse order, the inner loop is executed one required, the internal number of cycles (n-1) / 2, so the total number of cycles n (n-1) / 2, the algorithm complexity is O (n ^ 2)

  • Consider the best case, that the whole sequence is the order, the inner loop needs not performed, into a single double-loop cycle, so the total number of cycles is n, the complexity of the algorithm is O (n)

  • An average case, complexity of the algorithm is O (n ^ 2)

Complexity (2) Spatial Analysis

Additional auxiliary space is only a temp, and therefore the space complexity is O (1)

(3) Stability

If the two key value records A and B are equal, A first insert, the insert B, A sorted this time, the order of B remains the same, so this known sorting algorithm is stable.

Guess you like

Origin blog.csdn.net/starter_____/article/details/93928127