算法-基本排序:冒泡、选择、插入

本文详细介绍了选择排序、插入排序和冒泡排序的基本原理、核心思想及其实现过程,并通过实例代码展示了每种排序算法的特点与性能差异。重点强调了算法时间复杂度O(n)的应用场景,帮助读者理解不同排序算法的适用范围。

基本排序

在基本排序中有选择、插入、冒泡。在选择排序中最大的优势是:任务请求的少,是找到之后进行交换。

冒泡算法就是要一步一步的往上走。不能像选择排序这样只记得跳过数组中其它的元素。冒泡排序比较次数接近插入排序的两倍。移动次数与插入排序相同。选择排序,比较次数是一样的,而移动次数比冒泡多n次。So插入比冒泡快两倍。

对于插入来说一个非常好的情况是已经排好序就不用移动数据了。当然冒泡也是一样的,这些的时间复杂度均为O(n).


template<class T>
bool BaseSort<T>::bubbleSort(T *bubbleArray,int length)
{
	//主要思想:将最大元素往前走
	for (int index=0;index<length;index++)
	{
		T temp;
		cout<<index<<"次"<<endl;
		for (int j=length-1;j>index;j--)
		{
			temp=*(bubbleArray+j);
			if (*(bubbleArray+j-1)<*(bubbleArray+j))
			{
				*(bubbleArray+j)=*(bubbleArray+j-1);
				*(bubbleArray+j-1)=temp;
			}
			for (int k=0;k<10;k++)
			{
				cout<<bubbleArray[k]<<" ";
			}
			cout<<endl;
		}
		
	}
	return true;
}

template<class T>
bool BaseSort<T>::insertSort(T* insertArray,int length)
{
	//主要思想:从第一个开始将元素放入正确的位置,后面的元素根据前面的元素进行判断要放置的位置。
	//所以插入排序针对已经排序好的数组具有非常好的效率。
	for (int index=1;index<length;index++)
	{		
		T temp=*(insertArray+index);
		int j=index;
		while(j>0&&*(insertArray+j-1)>temp)
		{
			*(insertArray+j)=*(insertArray+j-1);
			j--;
		}
		*(insertArray+j)=temp;
		for (int k=0;k<10;k++)
		{
			cout<<*(insertArray+k)<<" ";
		}	
		cout<<endl;
	}
	return true;
}

template<class T>
bool  BaseSort<T>::selectSort(T *selectArray,int length)
{//选择排序
 //思想:先找到数组中最小的元素,将其与第一个位置上的元素进行交换,后面一样
	for (int index=0;index<length;index++)
	{
		int location=index;
		T temp=*(selectArray+index);
		for (int i=index;i<length;i++)
		{
			if (*(selectArray+location)>*(selectArray+i))
			{
				location=i;
			}
		}
		
		*(selectArray+index)=*(selectArray+location);
		*(selectArray+location)=temp;
		for (int j=0;j<10;j++)
		{
			cout<<selectArray[j]<<" ";
		}
		cout<<endl;
	}
return true;
}

小结:关键还是索引的问题。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值