插入排序&希尔排序(C/C++)
插入排序:
int main(void) { int beauties[] = { 2, 1, 4, 6, 8, 5, 9, 7, 5 }; int len = sizeof(beauties) / sizeof(beauties[0]); int preindex = 0, current = 0; for (int i = 1; i < len; i++) { preindex = i - 1; current = beauties[i]; while (preindex >= 0 && beauties[preindex] > current) { beauties[preindex+1] = beauties[preindex ]; preindex--; } beauties[preindex + 1] = current; } for (int i = 0; i < len; i++) { cout << beauties[i] << endl; } return 0; }
希尔排序:
int main(void) { int beauties[] = { 163, 161, 158, 165, 171, 170, 163, 1, 2 }; int len = sizeof(beauties) / sizeof(beauties[0]); int gap = len / 2; for (; gap > 0; gap = gap / 2) { for (int i = gap; i < len; i++) { int current = beauties[i]; int j = 0; for (j = i - gap; j >= 0 && beauties[j] > current; j -= gap) { beauties[j + gap] = beauties[j]; } beauties[j + gap] = current; } } for (int i = 0; i < len; i++) { cout << beauties[i] << endl; } return 0; }