-
常见算法效率比较
-
冒泡排序:依次比较相邻数据并根据排序规则交换;
-
插入排序:将当前元素插入到当前元素之前的所有元素的最后一个大于/小于的位置,其他位置元素依次向后移动;
-
选择排序:对于每个位置,选择剩余元素最小/最大的元素;
-
希尔排序:使用gap = N /2,将相邻gap的元素进行比较和交换,之后不断缩小gap,gap = 1时停止;
-
快速排序:使用povit元素作为基准,将小的元素放在基准左边,大于的元素放入基准右边;
-
归并排序:递归思想,借助新的数组;
代码实现:
#include <iostream>
#include <vector>
using namespace std;
//快速排序
void fastSort(vector<int> &nums, int l, int r)
{if (l < r){int left = l;int right = r;int pivot = nums[left];while (left < right){// 从右向左找到第一个小于pivot值元素做替换while (left < right && nums[right] >= nums[left]){right--;}nums[left] = nums[right];// 从左向右查找第一个大于pivot的元素while (left < right && nums[left] <= nums[right]){left++;}nums[right] = nums[left];}//left == rightnums[left] = pivot;fastSort(nums, l, left - 1);fastSort(nums, left + 1, r);}
}//冒泡排序
void dubbleSort(vector<int> &nums)
{int n = nums.size();for(int i = 0;i < n-1;i++){for(int j = i + 1;j < n;j++){if(nums[i] > nums[j]){int temp = nums[i];nums[i] = nums[j];nums[j] = temp;}}}
}//插入排序
void insertSort(vector<int> &nums)
{for(int i = 1;i < nums.size();i++){int cur = nums[i];int pos = i-1;while(pos >= 0 && cur < nums[pos]){nums[pos + 1] = nums[pos];pos--;}nums[pos + 1] = cur; }
}//选择排序
void selectSort(vector<int> &nums)
{for(int i = 0;i < nums.size()-1;i++){int minPos = i;for(int j = i;j < nums.size();j++){if(nums[j] < nums[minPos]){minPos = j;}}//交换int temp = nums[minPos];nums[minPos] = nums[i];nums[i] = temp;}
}//希尔排序
void shellSort(vector<int> &nums)
{int gap = nums.size() / 2;while(gap > 0){for(int i = gap;i < nums.size();i++){int j = i;while(j >= gap && nums[j] < nums[j-gap]){int temp = nums[j];nums[j] = nums[j-gap];nums[j-gap] = temp;j = j - gap;}}gap /= 2;}
}//归并排序
void merge(vector<int> &nums,int left,int right)
{vector<int> temp(nums.size());int mid = left + (right - left) / 2;int p = left;int q = mid + 1;int k = left;//新数组指针while(p <= mid && q <= right){if(nums[p] <= nums[q]){temp[k++] = nums[p++];}else{temp[k++] = nums[q++];}}while(p <= mid){temp[k++] = nums[p++];}while(q <= right){temp[k++] = nums[q++];}for(int i = left;i <= right;i++){nums[i] = temp[i];}}
void mergeSort(vector<int> &nums,int left,int right)
{if(left < right){int mid = left + (right - left) / 2;mergeSort(nums,left,mid);mergeSort(nums,mid+1,right);merge(nums,left,right);}
}
int main()
{vector<int> nums = {3, 2, 3, 1, 2, 4, 5, 5, 6};//快速排序fastSort(nums, 0, nums.size() - 1);//冒泡排序dubbleSort(nums);//插入排序insertSort(nums);//选择排序selectSort(nums);//希尔排序shellSort(nums);//归并排序mergeSort(nums,0,nums.size()-1);//输出结构for(auto a : nums){cout << a << " ";}return 0;
}