学习之余,实现三种最基本的排序算法,虽然不知道以后能用在哪里,先熟悉一下吧~下面给出实现算法以及测试代码:
参考博文:http://blog.youkuaiyun.com/hguisu/article/details/7776068
http://blog.youkuaiyun.com/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");
}
注释均用英文编写,应该还比较详细。有错误的地方,希望拍砖指正~