voidprintArr(int* arr, int len){ for(int i = 0; i < len; i++) cout<<arr[i]<<" "; cout<<endl; }
int 值对换
1 2 3 4 5
voidswap(int* a, int* b){ int tmp = *a; *a = *b; *b = tmp; }
排序算法
冒泡排序
1 2 3 4 5 6
voidbubbleSort(int* arr, int len){ for(int i = 0; i < len; i++) for(int j = i; j < len; j++) if(arr[i] > arr[j]) swap(&arr[i], &arr[j]); }
插入排序
1 2 3 4 5 6 7 8 9
voidinsertSort(int* arr, int len){ for(int i = 1; i < len; i++){ int cur = arr[i], j = i - 1; while(j >= 0 && arr[j] > cur) // Attention that arr[j + 1] = arr[j--] is wrong. arr[j-- + 1] = arr[j]; arr[j + 1] = cur; } }
Shell 排序:略微优化的插入排序
1 2 3 4 5 6 7 8 9 10 11 12 13
voidshellSort(int* arr, int len){ for(int gap = len >> 1; gap > 0; gap >>= 1){ for(int i = gap; i < len; i += gap){ int cur = arr[i]; int j = i - gap; while(j >= 0 && arr[j] > cur){ arr[j + gap] = arr[j]; j -= gap; } arr[j + gap] = cur; } } }