复习-快排
因为打算去找实习了,所以把之前学过、写到简历上的算法再复习一遍
冒泡排序
首先,快排是对冒泡排序的优化,那么回顾一下冒泡排序是怎么样的?
思路
冒泡排序是基于比较的排序
- 对于待排序列,从第一个元素开始,将当前元素与后一个元素作比较,如果>(<),则将两个元素交换位置
- 这样一轮结束后,序列末尾就变成了最大(小)的那个元素
这个过程就像是气泡的上浮一样,因此得名
- 重复上面的步骤,最终完成整个序列的排序
代码实现
void bubbleSort(int a[], int len) { // 这里是升序排序 // 其实一嵌套for循环就想到了双指针 // i指针指向的是“未排序的最后一个元素”,i的右边都是已经排好的元素 // j指针指向的是“当前与下一元素进行比较的数”,下一元素也用j指针+1来表示 for (int i = len - 1; i >= 0; --i) { for (int j = 0; j < i; ++j) { if (a[j] > a[j + 1]) { swap(a[j], a[j + 1]); } } } } int main() { int array[] = { 6,1,9,3,4,2,8,7 }; bubbleSort(array, 8); for (int i : array) { cout << i << " "; } // 输出:1 2 3 4 6 7 8 9 return 0; }
补一个参考的Java代码,因为实习是找Java,虽然说用C++写算法也不是不行,但还是避免不必要的麻烦,做好准备吧
菜鸟给的代码莫名其妙,还要加一个flag(可能有优化,但我没认真去想)
public static void bubbleSort(int[] arr){ // Java这里直接就相当于传引用了 // 不想原数据被更改的话,要把参数复制一个并返回 for (int i = arr.length-1;i>=0;--i){ for (int j = 0; j < i; ++j) { if (arr[j] > arr[j + 1]) { int tmp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = tmp; } } } } public static void main(String[] args) { int[] arr = {6,9,1,4,2,7,5}; bubbleSort(arr); for(int i:arr){ System.out.print(i+" "); } }
快速排序
快排是对冒泡的优化,时间复杂度从O(n2)变成了O(n logn),但是却从一个稳定算法变成了一个不稳定算法
思路
- 从待排序列中挑出一个”基准“(pivot)
- “分区”操作:将待排序列中比”基准”小的放左边,比”基准“大的放右边
- 递归地对子序列进行以上操作
代码实现
感觉自己目前只能做到在理解的基础上把它写出来,却不知道它是怎么被写出来的,即算法的精髓
#include <iostream> #include <algorithm> #include <time.h> #include <stdlib.h> using namespace std; int RandomInRange(int start, int end) { srand(time(NULL)); return rand() % (end - start + 1) + start; } int Paritition(int data[], int length, int start, int end) { if (data == nullptr || length < 0 || start < 0 || end >= length) { throw new exception("Invalid Parameters"); } int index = RandomInRange(start, end); swap(data[index], data[end]); int small = start - 1; for (index = start; index < end; ++index) { if (data[index] < data[end]) { ++small; if (small != index) { swap(data[small], data[index]); } } } ++small; swap(data[small], data[end]); return small; } void QuickSort(int data[], int length, int start, int end) { if (start == end) return; int index = Paritition(data, length, start, end); if (start < index) { QuickSort(data, length, start, index - 1); } if (end > index) { QuickSort(data, length, index + 1, end); } } int main() { int test[9] = { 5,2,8,3,6,4,9,7,1 }; QuickSort(test, 9, 0, 8); for (int a : test) { cout << a << " "; } }
本文作者:YaosGHC
本文链接:https://www.cnblogs.com/yaocy/p/16306466.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步