/*002:几种简单排序算法*/ 插入排序、冒泡排序、选择排序
/*插入排序--InsertionSort,从第二个元素开始,在前面找合适的位置插入*/
void InsertionSort(int a[], int len)
{
int i,j;
int temp;
for (i = 1; i < len - 1; i++)
{
temp = a[i];
j = i - 1;
while ( a[j] > temp && j >= 0)
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = temp;
}
}
/*二分插入排序--BinaryInsertionSort,从第二个元素开始,在前面折半找合适的位置插入*/
void BinaryInsertionSort(int a[], int len)
{
int i, j;
int low, high, mid;
int temp;
for (i = 1; i < len - 1; i++)
{
temp = a[i];
j = i - 1;
low = 0;
high = i - 1;
while (low <= high)
{
mid = (low + high)/2;
if (a[mid] > temp)
high = mid - 1;
else
low = mid + 1;
}
for (j = i; j >= low; j--)
a[j] = a[j - 1];
a[low] = temp;
}
}
/*冒泡排序--BubbleSort,交换相邻的,将本轮最大的放在最后*/
void BubbleSort(int a[], int len)
{
int i, j;
int temp;
bool exchanged;
for (i = len - 1; i > 0; i--)
{
exchanged = false;
for (j = 1; j <= i; j++)
{
if (a[j - 1] > a[j])
{
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
exchanged = true;
}
}
if (!exchanged) /*若某次冒泡过程中没发生交换,则排序结束*/
return ;
}
}
/*选择排序--SelectSort,选择最小的放在前面*/
void SelectSort(int a[], int len)
{
int i,j,k;
int temp;
for (i = 0; i < len - 1; i++)
{
k = i;
for (j = i + 1; j < len - 1; j++)
{
if (a[j] < a[k])
k = j;
}
if (k != i)
{
temp = a[k];
a[k] = a[i];
a[i] = temp;
}
}
}