#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void quickSort(vector<int> &nums);
void quick_sort(vector<int> &nums, int l, int r);//快排
//归并排序
void mergeSort(vector<int> &nums);
void merge_sort(vector<int> &nums, int l, int r, vector<int> &temp);
//堆排序
void heapSort(vector<int> &nums);
void buildMaxHeap(vector<int> &nums,int len);//创建最大堆
void maxHeapify(vector<int> &nums,int i ,int len);
//插入排序
void insertion_sort(vector<int> &nums, int n) {
for (int i = 0; i < n; i++)
{//一个一个 插入, 左边成为有序的
for (int j = i; j > 0 && nums[j] < nums[j - 1]; j--)
swap(nums[j], nums[j - 1]);//因为 n为刚刚插入的值
}
}
int findKthLargest(vector<int>& nums, int k);
int main()
{
vector<int> p{1,2,9,20,49,19,48,3,4};
heapSort(p);
}
void quickSort(vector<int>& nums)
{//快排
quick_sort(nums, 0, nums.size() - 1);
}
void quick_sort(vector<int>& nums, int l, int r)
{
if (l >= r)
return;
int left = l, right = r; int pos=left;
while (left < right)
{
while (left < right && nums[pos] >= nums[right])right--;
while (left < right && nums[pos] <= nums[left])left++;
if (nums[left]< nums[right])
swap(nums[left],nums[right]);
}
if (nums[left] > nums[pos])
swap(nums[left], nums[pos]);
quick_sort(nums, pos, left);
quick_sort(nums, left +1,r);
}
void mergeSort(vector<int>& nums)
{
int size = nums.size();
vector<int> temp(size);
merge_sort(nums,0, size-1,temp);
}
void merge_sort(vector<int>& nums, int l, int r, vector<int>& tmp)
{
if (l >= r) return;
int mid = (l + r) >> 1;
merge_sort(nums, l, mid,tmp);
merge_sort(nums, mid + 1,r,tmp);
int i = l, j = mid + 1;
int cnt = l;
while (i <= mid && j <= r) {
if (nums[i] <= nums[j]) {
tmp[cnt++] = nums[i++];
}
else {
tmp[cnt++] = nums[j++];
}
}
while (i <= mid) {//只有一个 会放完,一个不会放完
tmp[cnt++] = nums[i++];
}
while (j <= r) {
tmp[cnt++] = nums[j++];
}
for (i = l; i <= r; ++i) {//l到 r的数据 赋值即可
nums[i] = tmp[i];
}
}
void heapSort(vector<int>& nums)
{
int len = nums.size() - 1;
buildMaxHeap(nums, len);//简历堆
for (int i = len; i >= 1; i--)//堆排序
{
swap(nums[i],nums[0]);//交换最大值
len--;
maxHeapify(nums, 0, len);//重新定义堆
}
}
void buildMaxHeap(vector<int>& nums, int len)//右端 端点
{
for (int i = len / 2; i >= 0; --i)
maxHeapify(nums,i,len);
}
void maxHeapify(vector<int>& nums,int i,int len)//下沉
{
for (; (i << 1) + 1 <= len;) //加2成立
{
int lson = (i << 1) + 1;//左树
int rson = (i << 1) + 2;//右树
int large;
if (lson <= len && nums[lson] > nums[i]) {
large = lson;
}
else {
large = i;
}
if (rson <= len && nums[rson] > nums[large]) {
large = rson;
}
if (large != i) {
swap(nums[i], nums[large]);
i = large;//往下 遍历
}
else { //直到 两边都小于 中间的最大堆值
break;
}
}
}
leetcode之常用排序
最新推荐文章于 2024-11-03 16:33:21 发布