自己实现了一遍冒泡排序、选择排序、插入排序,留个念想
冒泡排序
简单来说就是从数组末端冒泡到数组当前位置
void bubblesort(unsigned char *data, unsigned short length)
{
unsigned short i,j;
unsigned char temp;
if (length <= 0) return;
for (i = 0; i < length - 1; i++)
{
for (j = length - 1; j>i; j--)
{
if (data[j] < data[j-1])
{
temp = data[j];
data[j] = data[j-1];
data[j-1] = temp;
}
}
}
}
选择排序 当前位置之后的所有数跟当前位置的数比较,得到最小的数到当前位置
void select_sort(unsigned char *data, int length)
{
int i, j;
int min;
unsigned char temp;
for (i = 0; i < length; i++)
{
min = i;
for (j = i + 1; j < length; j++)
{
if (data[j] < data[min])
min = j;
}
if (min != i)
{
temp = data[min];
data[min] = data[i];
data[i] = temp;
}
}
}
插入排序 当前位置以下挪出一个适合的位置来放当前位置数据
void insert_sort(unsigned char *data, int length)
{
int i, j;
unsigned char min;
for (i = 0; i < length; i++)
{
min = data[i];
for (j = i; j>0; j--)
{
if (data[j - 1] > min)
data[j] = data[j - 1];
else
break;
}
data[j] = min;
}
}
折半查找
int bi_find(unsigned char n, unsigned char *data, int length)
{
int min, max, mid;
//unsigned char temp;
int ret = 0;
min = 0;
max = length - 1;
mid = (min + max) / 2;
while (max >= min)
{
if (data[mid] == n)
{
ret = mid;
break;
}
else if (data[mid] < n)
min = mid+1;
else if (data[mid]>n)
max = mid-1;
mid = (min + max) / 2;
}
return ret;
}