插入排序伪代码:
INSERTION-SORT(A)
for j ←2 to length[A]
do key ← A[j]
▷ insert A[j] into the sorted sequence A[1...j-1]
i ← j-1
while i>0 and A[i]>key
doA[I+1] ← A[i]
i ← i-1
A[i+1] ← key
C语言代码:
/*
n --- 数组长度
升序排列
*/
void insert_sort(sort_t *sort, int n)
{
int i, j;
sort_t key;
for(j = 1; j < n; j++)
{
key = sort[j];
// 将sort[j]插入到已经排好序的数组sort[0...j-1];
i = j - 1;
while(i > -1 && sort[i] > key)
{
sort[i+1] = sort[i];
i--;
}
sort[i+1] = key;
}
}
int main(void)
{
sort_t a[10] = {10,2,3,40,5,6,7,8,9,10};
insert_sort(a, 10);
for(int i = 0; i < 10; i++)
printf("%d,", a[i]);
printf("\n");
return 0;
}冒泡排序伪代码:
BUBBLESORT(A)
for(i←1 to length[A])
do for j←length[A] downto i+1
do if A[j] < A[j-1]
then exchange A[j]↔A[j-1]C语言代码:
typedef int sort_t;
#define swap(x, y) temp = y, y = x, x = temp
/*
冒泡排序
逐个交换,每轮之后最小值被“冒”到最前面
*/
void bubblesort(sort_t *A, int length)
{
sort_t temp;
int i, j;
for(i = 0; i < length; i++)
{
for(j = i+1; j < length; j++)
{
if(A[i] > A[j])
{
swap(A[i], A[j]);
}
}
}
}
18万+

被折叠的 条评论
为什么被折叠?



