void InsertSort(int nLen) { for (int i = 1; i < nLen; i++) { int j = i - 1; while (g_szArray[j] > g_szArray[i]) { j--; if (j < 0) { break; } } if (j == i - 1) { continue; } int tmp = g_szArray[i]; int k = i; while (k > j) { g_szArray[k] = g_szArray[k - 1]; k--; } g_szArray[j + 1] = tmp; } }
优化一下代码的逻辑:
void InsertSort2(int nLen) { for (int i = 1; i < nLen; i++) { int tmp = g_szArray[i]; int j = i - 1; while (g_szArray[j] > tmp && j > 0) { g_szArray[j + 1] = g_szArray[j--]; } g_szArray[j + 1] = tmp; } }