/* 目录: 一 插入排序 二 希尔排序 */
一 插入排序
#include <iostream> using namespace std; void Print_Array(int* p, int nCount); void InsertionSort(int* p, int nCount) { int i = 1; // 初始值 while (i < nCount) // 控制外层循环 { int key = p[i]; // 数组[1] int j = i - 1; // 数组[0] while (j >= 0 && p[j] > key) // 结束条件: 1 循环到数组头部; 2 Key前数值 小于Key { p[j + 1] = p[j]; // 数据赋值 : 前值 - 后值 --j; // 数组遍历 : 前 - 后 } p[j + 1] = key; // 找到位置 : 插入数值 ++i; } } void Print_Array(int* p, int nCount) { int nLoop = 0; while (nLoop < nCount) { printf("0x%x ", p[nLoop]); ++nLoop; } printf("\n"); } int main() { int nNum[] = { 0x88, 0x22, 0x10, 0x3, 0x5}; int nCount = sizeof(nNum) / sizeof(nNum[0]); Print_Array(nNum, nCount); InsertionSort(nNum, nCount); Print_Array(nNum, nCount); return 0; } /* // result 0x88 0x22 0x10 0x3 0x5 0x3 0x5 0x10 0x22 0x88 */
二 希尔排序
void ShellSort(int* p, int nCount) { int inc = nCount / 2; while (inc > 0) { printf("inc: %d\n", inc); Print_Array(p, nCount); int i = inc; while (i < nCount) { int key = p[i]; int j = i; while (j >= inc && p[j - inc] > key) { p[j] = p[j - inc]; j = j - inc; } p[j] = key; ++i; } inc = inc / 2; } } int main() { // int nNum[] = { 66, 77, 88, 5, 55, 0, 22, 10, 3}; int nNum[] = { 66, 2, 6, 77, 7, 88, 99, 54, 62, 100, 5, 50, 55, 0, 6, 22, 166, 98, 10, 3 }; int nCount = sizeof(nNum) / sizeof(nNum[0]); Print_Array(nNum, nCount); shell_sort(nNum, nCount); Print_Array(nNum, nCount); return 0; }