例题:
/*这是降序,升序只需将while循环改成: while(key<a[i]) */ #include "stdafx.h" #include<iostream> using namespace std; void insertSort(int a[], int length) { int i = 0; int j, key; for (j = 1; j < length; j++) { key = a[j]; i = j - 1; while (key > a[i]) { int tmp; tmp = a[i + 1]; a[i + 1] = a[i]; a[i] = tmp; i = i - 1; if (i < 0){ break; } } } } int _tmain(int argc, _TCHAR* argv[]) { int a[7] = { 1, 4, 5, 22, 33, 44, 55 }; insertSort(a, 7); int i; for (i = 0; i < 7; i++) { cout << a[i] << endl; } return 0; }
#include "stdafx.h" #include<iostream> using namespace std; int searchQuestion(int a[],int length,int v) { int i, key=0; for (i = 0; i < length; i++) { if (v == a[i]){ cout << v << endl; key++; } } return key; } int _tmain(int argc, _TCHAR* argv[]) { int a[10] = { 3, 3, 4, 5, 6, 7, 2, 33, 55 }; int v; while (cin >> v){ int value = searchQuestion(a, 10, v); if (value == 0){ cout << "NIT" << endl; } } return 0; }
/* CLRS 2.1.4 */ #include "stdafx.h" #include<iostream> using namespace std; void convert(int a[], int n) { int i; int temp; for (i = 0; i<n / 2; i++) { temp = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = temp; } } int *sum(int a[], int lengtha, int b[], int lengthb) { convert(a, lengtha); convert(b, lengthb); int lengthc = lengtha>lengthb ? lengtha : lengthb; lengthc += 1; int *c = new int[lengthc]; memset(c, 0, lengthc); int i, key = 0; for (i = 0; i<lengthc; i++) { if (lengtha <= i) { if (lengthb>i) { c[i] = b[i] + key; if (c[i] >= 2) { c[i] %= 2; key = 1; } else { key = 0; } } else { c[i] = key; } } else if (lengtha>i) { if (lengthb>i) { c[i] = a[i] + b[i] + key; } else { c[i] = a[i] + key; } if (c[i] >= 2) { c[i] %= 2; key = 1; } else { key = 0; } } } return c; } int main() { int a[10] = { 1, 0, 1, 0, 1, 1, 0, 0, 1, 1 }; int b[9] = { 1, 0, 0, 0, 1, 0, 0, 0, 0 }; int *c; int i, key; c = sum(a, 10, b, 9); for (i = 10; i >= 0; i--) { if (c[i] != 0) { key = i; break; } } for (i = key; i >= 0; i--) { cout << c[i] << " "; } return 0; }
原文地址:http://blog.csdn.net/p641290710/article/details/41801701