快排和堆排序
来源:互联网 发布:5357端口 编辑:程序博客网 时间:2024/05/16 01:46
别看这个简单也基础,但是真的面试的时候会让你写,纸上手写,嗯
快排
private static void quickSort(int[] test, int start, int end) { //quick sort的主程序 if(start < end){ int q = partition(test, start, end); quickSort(test, start, q-1); quickSort(test, q+1, end); } } private static int partition(int[] test, int start, int end) { //完成一次划分 //主元选择test[end] int pivot = test[end]; int i = start - 1; for(int j = start; j < end; j++){ if(test[j] <= pivot){ i++; //交换test[i]和test[j] int t = test[i]; test[i] = test[j]; test[j] = t; } } //i+1的位置即是pivot的位置 //交换test[i+1]和pivot int t1 = test[i+1]; test[i+1] = test[end]; test[end] = t1; return i+1; }
堆排序
public static void heapSort(int[] test){ //建堆 buildHeap(test); for(int heapSize = test.length - 1; heapSize >= 1; heapSize--){ //交换test[heapSize]和test[0]的位置 int t = test[0]; test[0] = test[heapSize]; test[heapSize] = t; //维护堆的性质 maxHeapify(test, heapSize, 0); } } private static void maxHeapify(int[] test, int heapSize, int i) { //维护堆的性质 int left = 2 * i + 1; int right = 2 * i + 2; //找出三者最大的 int largest; if(left < heapSize && test[left] > test[i]){ largest = left; }else{ largest = i; } if(right < heapSize && test[right] > test[largest]){ largest = right; } if(i != largest){ //交换test[i]和test[largest] int t = test[i]; test[i] = test[largest]; test[largest] = t; //递归 maxHeapify(test, heapSize, largest); } } private static void buildHeap(int[] test) { //建堆 for(int i = test.length / 2; i >= 0; i--){ maxHeapify(test, test.length, i); } }
main函数:
int test = {2,3,1,1,5,6,7,7,8,4,9,11};//quickSort(test, 0, test.length-1);heapSort(test);for(int x : test){ System.out.print(x+" ");}
0 1
- 快排和堆排序
- 快排和堆排序
- 快排、堆排序
- 快排和堆排序对比
- 快排和堆排序分析
- java 快排和堆排序
- 快排、堆排和归并排序的Python实现
- SDNU__1521.排序——堆排和快排
- 排序(快排,归并,堆排)
- 快排 和 堆排序算法的细节代码分析
- poj2388 堆排序和快排的练手
- TOP-K问题-堆排序和快排实现
- 堆排序、快排的坑
- 快排、归并、堆排序运用场景
- 快排,堆排序,基数排序手写记录
- 堆排序、归并、快排、BSTree
- 快排、堆排序、插入法比较
- 快排和归并排序
- Python3入坑指南(01) -- Python的关键要素
- [BZOJ 1725][Usaco2006 Nov]Corn Fields牧场的安排:状压DP
- LintCode-两数组的交集
- spring 回滚事务 异常处理 手动回滚 公司通用处理方式
- Web基础之与Tomcat的初次相遇
- 快排和堆排序
- 关于HTML--结构化标签
- 自定义View之柱状图
- 关于Java面向对象之封装
- 杭电acm1016 Prime Ring Problem
- Java创建线程(Runnable接口和Thread类)
- 有关socket通信包大小的问题总结(UDP传输模式)
- 传奇客户度文件代码完全解析
- Collection和Map的那些常用的类操作的实现原理简要理解笔记