菜鸟学编程之三:三种最基本排序算法的实现(冒泡排序、选择排序、直接插入排序)

学习之余,实现三种最基本的排序算法,虽然不知道以后能用在哪里,先熟悉一下吧~下面给出实现算法以及测试代码:

参考博文:http://blog.csdn.net/hguisu/article/details/7776068

http://blog.csdn.net/cjf_iceking/article/details/7916194

<pre name="code" class="cpp">#include<stdio.h>
#include<stdlib.h>
#include<time.h>

//bubble sort method
void bubbleSort(int *srcData, int len)
{
	int i,j;
	int temp;
	for(i = 0; i < len-1; i++)
	{
		for(j = 0; j< len - i -1 ; j++)
		{
			if(srcData[j] > srcData[j + 1])
			{
				temp = srcData[j];
			srcData[j] = srcData[j + 1];
			srcData[j + 1] = temp;
			}
		}
	}
}

//select sort method
void selectSort(int srcData[], int len)
{
	int i,j;
	int temp; //save the temporary number
	int index; //the index for finding the minimum number in the array
	for(i = 0; i < len - 1; i++)
	{
		index = i;
		for(j = i+1; j < len; j++)
			if(srcData[index] > srcData[j]) //find the minimum index
			{
				index = j;
			}
			if(index != i) //swap 
			{
				temp = srcData[index];
				srcData[index] = srcData[i];
				srcData[i] = temp;
			}
	}
}

//straight insert sort method
void inertSort(int srcData[], int len)
{
	int i,j;
	int temp;
	for(i = 1; i < len; i++)
	{
		//if the value of i is greater than the value of i-1,insert straightly;
		//otherwise, move the ordered list and then insert 
        if(srcData[i] < srcData[i-1]) 
		{              
            j= i-1;
            temp = srcData[i]; //save a temparary number which is waiting for being sorted
            srcData[i] = srcData[i-1];  //move back to one elemet  
            while(temp < srcData[j]) //find the insert position from the ordered list
			{   
                srcData[j+1] = srcData[j];  
                j--; //move back the elements  
            }  
            srcData[j+1] = temp; //insert into the right pisition
        }
	}
}

void main()
{
	int N = 10;
	srand((unsigned)time(NULL));
	int i,j;
	int *srcData = new int[N];
	printf("This is the original random data: \n");
	for(i = 0; i < N; i++)
	{
		srcData[i] = rand()%100+1;
		printf("%d ",srcData[i]);
	}
	printf("\n");

	//bubbleSort(srcData,N);
	//selectSort(srcData,N);
	inertSort(srcData,N);
	printf("This is the sorted data: \n");
	for(i = 0; i < N; i++)
	{
		printf("%d ",srcData[i]);
	}
	printf("\n");
	system("pause");
}


 注释均用英文编写,应该还比较详细。有错误的地方,希望拍砖指正~ 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值