关于练习程序的说明参见置顶的那篇。
2.1-1:
31 41 59 26 41 58
31 41 59 26 41 58
31 41 59 26 41 58
26 31 41 59 41 58
26 31 41 41 59 58
26 31 41 41 58 59
2.1-2:
#include <stdio.h> void inverseInsertSort(int a[], int n); int main(int argc, char *argv[]) { int i; int a[6] = {31, 41, 59, 26, 41, 58}; inverseInsertSort(a, 6); for(i=0; i<6; i++) printf(" %d ", a[i]); printf(" "); return 0; } void inverseInsertSort(int a[], int n) { int i,j,key; for(i=1; i<n; i++) if(a[0] < a[i]) { key = a[i]; a[i] = a[0]; a[0] = key; } for(i=2; i<n; i++) { key = a[i]; j = i - 1; while(key > a[j]) { a[j+1] = a[j]; j--; } a[j+1] = key; } }
2.1-3:
int linearSearch(int a[], int n, int value) { int i; for(i=0; a[i]!=value && i<n ; i++); return i<n ? i: -1; }
初始化:i=0
循环:a[i] !=value && i<n
结束: a[i] = value || i=n
因为i从0开始增加,所以一定会结束循环
2.1-4:
void addNBits(int n1[], int n2[], int sum[], int n) { int i, flag=0; for(i=0; i<n; i++) { sum[i] = n1[i] + n2[i] + flag; flag = sum[i] >> 1; sum[i] %= 2; } sum[n] = flag; }