sorting 应该是最容易被考到的东西,自己老是学了背,背了忘。为了方便复习,这里进行总结

1. Bubble Sort

定义:每两个两个比较,每扫完一次,当前扫过的最大值放在了末尾。

for i = (n-1) to 1
for j = 0 to i-1
if(A[j] > A[j+1])
swap

  Time Complexity:

Best case : O(n) It can occur if the array is already sorted and no swap occurred.

Worse case: O(n^2)

2. Insertion Sort

定义:当前element 的之前所有elements 都已排好序。把当前element 放进之前排好序的数列中的正确位置。(当前的element从后向前比较)

Insertion sort takes advantage of the presorting. It requires fewer comparision than bubble sort

 for i = 1 to n -1
j = i
while j >0 and A[j] <A[j-1]
swap(A[j], A[j-1])
j --;

  Time Complexity:

Best case : O(n)

Worse case:  O(n ^2)

3. Merge Sort

定义:把一个数组打散看成一个一个的单独的,然后每两个两个组一组,merge,新的组合再两个两个组一组,merge

# C = output [length = N]
# A 1st sorted half [N/2]
# B 2nd sorted half [N/2]
i = j = 1
for k = 1 to n
if A[i] < B[j]
C[k] = A[i]
i++
else
C[k] = B[j]
j++

  

Time Complexity:  O(nlgN)

4. Quick sort

定义: 随机选一个pivot( 当然ideally 是 medium), pivot 的左边全是比自己小的数,右边全是比自己大的数

所以有两个指针,一个指头,一个指尾,第一个指针指向第一个elemnt > pivot 的位置, 第二个指针从后往前,指向第一个element 小于pivot的位置

然后swap。如此扫一遍。然后以pivot为界限,array 分为两部分,再分别选一个pivot,继续上面的过程

Quicksort(A as array, low as int, high as int){
if (low < high){
pivot_location = Partition(A,low,high)
Quicksort(A,low, pivot_location)
Quicksort(A, pivot_location + 1, high)
}
}
Partition(A as array, low as int, high as int){
pivot = A[low]
leftwall = low for i = low + 1 to high{
if (A[i] < pivot) then{
swap(A[i], A[leftwall])
leftwall = leftwall + 1
}
}
swap(A[low],A[leftwall]) return (leftwall)}

  

Time complexity:  O(nlogn)

5. Selection Sort

定义: 选到第一小的,跟第一个element swap, 然后选第二小的,跟第二个element swap

SELECTION-SORT(A)
1. for j ← 1 to n-1
2. smallest ← j
3. for i ← j + 1 to n
4. if A[ i ] < A[ smallest ]
5. smallest ← i
6. Exchange A[ j ] ↔ A[ smallest ]

  

Complexity: O(n^2)

最新文章

  1. ASP.Net中通过Jquery前端对Repeater控件绑定的数据进行操作
  2. $_SERVER 的用法
  3. Eclipse下.project和.classpath作用(转)
  4. Linux中的likely()和unlikely()
  5. CentOS下FTP服务器安装与配置
  6. 14.4.3 Adaptive Hash Index 自适应hash index
  7. 64位linux中使用inet_ntoa报错处理
  8. 最长回文(Manacher)
  9. vue table-tree 组件
  10. 怎样保证socket.recv接收完数据
  11. NoSQL数据库常见分类
  12. 在Ubuntu16上安装mininet和floodlight过程,超全篇
  13. HBase原理和架构
  14. TOJ 4829: 计算器的改良
  15. Spring restTemplate
  16. Windows7共享设置
  17. Configurations of Vim/GVim of dsp
  18. SpringBoot集成WebSocket【基于STOMP协议】进行点对点[一对一]和广播[一对多]实时推送
  19. [Jobdu] 题目1348:数组中的逆序对
  20. Netty 5 获取客户端IP(非HTTP)

热门文章

  1. delphi 功能函数大全-备份用
  2. hibernate使用sql语句查询实体时,要写上addEntity
  3. (五)Struts2 标签
  4. ARM开发板系统移植-----rootfs的制作
  5. ProfessionalKnowledgeArchitecture
  6. Python: 设计模式 之 工厂模式例(1)
  7. Laravel之路——file缓存修改为redis缓存
  8. Scut:账号服务器问题修正
  9. 运输层协议----UDP
  10. C++中Reference与指针(Pointer)的使用对比