template<typename T> voidadjust(vector<T>& nums, int len, int index){ int cur = index; int lchild = (index << 1) + 1, rchild = (index << 1) + 2; if(lchild < len && nums[lchild] > nums[cur]) cur = lchild; if(rchild < len && nums[rchild] > nums[cur]) cur = rchild; if(cur != index){ swap(nums[index], nums[cur]); adjust(nums, len, cur); } }
template<typename T> voidheapSort(vector<T>& nums){ int n = nums.size(); for(int i = n / 2 - 1; i >= 0; -- i){ adjust(nums, n, i); } for(int i = n - 1; i >= 1; -- i){ swap(nums[0], nums[i]); adjust(nums, i, 0); } }
希尔排序
1 2 3 4 5 6 7 8 9 10 11 12 13
template<typename T> voidshellSort(vector<T>& nums){ int n = nums.size(); for(int step = n / 2; step > 0; step /= 2){ for(int i = step; i < n; i += step){ for(int j = i - step; j > 0; j -= step){ if(nums[j] > nums[j + step]){ swap(nums[j], nums[j + step]); } } } } }
计数排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14
template<typename T> voidcountSort(vector<T>& nums){ int maxv = *max_element(nums.begin(), nums.end()), minv = *min_element(nums.begin(), nums.end()); int len = maxv - minv + 1; T cnt[len]; memset(cnt, 0, sizeof(cnt)); for(auto&& num : nums) ++ cnt[num - minv]; int index = 0; for(int i = 0; i < len; ++ i){ while(cnt[i] --){ nums[index ++] = i + 1; } } }
桶排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
template<typename T> voidbucketSort(vector<T>& nums){ int n=nums.size(); int maxv = *max_element(nums.begin(), nums.end()); int minv = *min_element(nums.begin(), nums.end()); int bucketCnt = (maxv - minv) / n + 1; vector<vector<T>> buckets(bucketCnt); for(auto& num : nums){ int bucketIdx = (num - minv) / bucketCnt; if(bucketIdx >= bucketCnt) bucketIdx = bucketCnt - 1; buckets[bucketIdx].push_back(num); } nums.clear(); for(auto& bucket : buckets){ sort(bucket.begin(), bucket.end()); for(int& num : bucket) nums.push_back(num); } }