Bubble / selection / insertion / exchange sort c language

Insertion Sort

void Insertion_sort(int a[A], int x)
{

	int m = 0;
	int ab = 0;
	int temp = 0;
	int ipos = 0;
	int n = 0;
	for (m = 1; m < x; m++)
	{
		temp = a[m];
		ipos = m - 1;
		while ((ipos >= 0) && (temp < a[ipos]))
		{
			a[ipos + 1] = a[ipos];
			ipos--;
		}
		a[ipos + 1] = temp;
	}
	for (m = 1; m < x; m++)//拿出一个数
	{
		temp = a[m];//用变量存放,数组中的值不要改变
		for (n = m - 1; n >= 0; n--)//这个数的前n个数
		{

			if (temp <= a[n]) //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
			{
				a[n + 1] = a[n];//则两数交换,然后在和
				if (n == 0)
				{
					a[0] = temp;
				}
			}
			if (temp > a[n])
			{
				a[n + 1] = temp;
				break;

			}

		}

		printf("\r");
	}

	}

Bubble Sort

int BubbleSort(int a[A], int x)
{
		int ab = 1;
		for (int trip = 0; trip < x; trip++)//控制比较的躺数!
		{
			int judge = 1;
			for (int i = 0; i < x - 1 - trip; i++)//每次从头开始,比较,每一趟可以少比一个,因为每一趟都把最大的数筛到最后了!
			{
				if (a[i] > a[i + 1])//两书交换
				{
					a[i] = a[i] ^ a[i + 1];
					a[i + 1] = a[i] ^ a[i + 1];
					a[i] = a[i] ^ a[i + 1];
					judge = 0;//判断!如果再一趟内,没有进行任何两数之间的交换,就不改变该zhi。从而检测,检测排序手机不是可以提前结束!从而避免不必要的多余的循环
					ab++;
				}

			}
			if (judge == 1)
			{
				printf("BubbleSort  %d!!!!!!!!!!!!!\n", ab);
				return 0;
			}
		}
	}

.

Selection Sort

int Selectionsort(int a[A], int x)
{
	int ab = 1;
	for (int trip = 0; trip < x-1; trip++)//
	{
		int mine = 0;
		mine = a[trip];//关键
		int subscript = trip;//关键
		for (int i = trip+1; i < x; i++)
		{
			if (mine > a[i])
			{
				mine = a[i];//记录最小的值
				subscript = i;//记录下标
				ab++;
			}
		
		}
		
		a[subscript] = a[trip];//两书交换,最小值赋值
		a[trip] = mine;//关键

	}
	printf("Selectionsort  %d!!!!!!!!!!!!!\n", ab);
	return 0;
}

Sort exchange

void Exchange(int a[A],int x)
{
	int ab = 1;
	for (int z = 0; z < x-1; z++)//每次的起始位置!如同拿出一个数,
	{
		for (int y = z+1; y < x; y++)//与这个数后面的每一个数比较

		{
			
			if (a[z] > a[y])
			{
				a[y] = a[y] ^ a[z];
				a[z] = a[y] ^ a[z];
				a[y] = a[y] ^ a[z];
				ab++;
			}
			
		}//将拿出来的这个数,和后面的数比较,比较完了之后,可以确保,拿出来的这个数是这个数和他以后的·所有数中最小/大的一个
		//然后拿出下一个数,再进行相同操作,拿出来的每个数都是再除去前面的数的 1其他数中的最值
	} 
	printf(" EXchange  %d!!!\n",ab);
	
}

By reducing the time of assignment when compared to large values ​​of each switching position, to achieve the purpose of optimized algorithms.

Row merge is learning fast. Road string pattern matching algorithm violence is about to appear, kmp are asking teachers 233

Published 13 original articles · won praise 13 · views 750

Guess you like

Origin blog.csdn.net/jiewaikexue/article/details/103339583