Introduced two priority - fast and bubble row

Quick Sort

Algorithm Description:
define left j i = L = R and the rightmost
taking the middle mid number as [/ 2 (R + l) ] determined mid = a
trip quick sort:
starting with the left are gradually increasing until the value of i the first find a [i]> mid out of the loop at this time
and then gradually decreases from the right until the first value of j a a [j] <mid case out of the loop
at this time should be satisfied both i <j in the that is, to keep i on the left and j on the right is consistent with part of small on the left and large data to the right
above conditions are met, then the exchange value each other
and the way increment i decrement j see meets i <j
is satisfied to continue the cycle
otherwise use recursion for small sequence reordering

void qSort(int a[],int l,int r)
{
	if (l > r) 
	{
		return;    //参数不对  退出
	}
	int i, j, mid, p;
	i = l;
	j = r;
	mid = a[(l + r) / 2];                  
	do
	{
		while (a[i] < mid) i++;     //如果左边第一个大于mid的数找到了 就退出循环 等待交换     
		while (a[j] > mid) j--;   //如果右边第一个小于mid的数找到了  就退出循环  
		if (i < j)  //判断  j的数是否是在i的右边
		{                                
			p = a[i];
			a[i] = a[j];
			a[j] = p;
			i++; //一定要对数据进行更新
			j--;                          
		}
		else if (i == j) 
		{
			i++;  //对序列的数据进行更新
			j--;
		
		}

	} while (i < j);                                 
	if (l < j)  qSort(a,l, j);      //再分别对子序列进行排序         
	if (i < r)  qSort(a,i, r);
}

Bubble Sort

Description:
comparing adjacent elements. If the first is greater than the second, the two of them exchanged.
Do the same work for each pair of adjacent elements, from the beginning of the first pair to the end of the last pair. At this point, it should be the last element is the largest number.
Repeat these steps for all elements, except the last one.
Continuing to repeat the above steps every time fewer and fewer elements, until there is no need to compare a pair of numbers
. 1. 9 10. 8 36. 5. 1 I =
. 8. 1. 5 36. 9 10
. 8 36. 5. 1. 9 10
. 8 10. 5 36. 1. 9
. 8 5 36. 9. 1 10
. 8 5 36. 9 10 1 performs five times
I = 2
. 8 5 36. 9 10. 1
. 8 36 5. 9 10. 1
. 8 36. 9 5 10. 1
. 8 36. 9 10 5. 1
is performed four times
i = 3
36. 5. 1. 8. 9 10
36. 8 10. 5. 1. 9
36. 8 10. 5. 9 1 performs three times

=. 4 I
36. 5. 1. 9 10. 8
36. 5 10. 1. 8. 9
performed twice
... (hereinafter do not need to re-compared need to be optimized so, and then compare that time, if the exchange has not occurred on the break DESCRIPTION lined up)
visible per trip of the number of comparisons is ni

void bSort(int a[], int n)  //n的值应该是元素的个数
{
	bool bo;
	int i = 1,temp;
	do
	{
		bo = true;    //优化做法  当下面没有发生交换的时候就退出循环  并且已经排序好了
		for (int j = 0; j < n - i; ++j) 
		{
			if (a[j] > a[j + 1]) 
			{
				temp = a[j];
				a[j] = a[j + 1];
				a[j + 1] = temp;
				bo = false;
			}
		}
		++i;
	} while (!bo);
}
发布了19 篇原创文章 · 获赞 3 · 访问量 3816

Guess you like

Origin blog.csdn.net/weixin_42792088/article/details/87386741