lintcode python代码 463 整数排序
来源:互联网 发布:mac os恢复模式 编辑:程序博客网 时间:2024/06/07 23:19
给一组整数,按照升序排序,使用选择排序,冒泡排序,插入排序或者任何 O(n2) 的排序算法。
思路:
冒泡法:遍历数组,把当前数字的后面所有的数字都遍历一遍,遇到小的跟当前数字交换,这样遍历的过程中,所有大的数字就像气泡一样都到数组的后面去了
class Solution: # @param {int[]} A an integer array # @return nothing def sortIntegers(self, A): for i in range(len(A)-1): for j in range(i+1,len(A)): if A[i]>=A[j]: A[i],A[j]=A[j],A[i] j+=1 print(A)M=Solution()B=[2,8,5,1]M.sortIntegers(B)
插入排序:有一个已经有序的数据序列,要求在这个已经排好的数据序列中插入一个数,但要求插入后此数据序列仍然有序,这个时候就要用到一种新的排序方法——插入排序法,插入排序的基本操作就是将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据
思路:从A[i]开始 如果小于前一个数,交换i-1 继续与前一个数比较 小于前一个数交换, i-1值为0时停止。
class Solution: # @param {int[]} A an integer array # @return nothingdef insertion_sort(A): for i in range(1, len(A)): save = A[i] j = i while j > 0 and A[j - 1] > save: A[j] = A[j - 1] j -= 1 A[j] = save return A
选择排序:思路是遍历数组,对于当前位置i,我们定义一个变量min_idx,用来记录当前位置往后的最小值的坐标,我们通过遍历之后所有的数字来找到最小值的坐标,然后交换A[i]和A[min_idx]即可
class Solution: # @param {int[]} A an integer array # @return nothing def sortIntegers(self, A): # Write your code here i = 0 j = len(A) - 1 self.quick_sort(A, i, j) def quick_sort(self, A, low, high): if low < high: i = low j = high tmp = A[low] while i < j: while i < j and A[j] >= tmp: j -= 1 A[i] = A[j] while i < j and A[i] < tmp: i += 1 A[j] = A[i] A[i] = tmp self.quick_sort(A, low, i-1) self.quick_sort(A, i+1, high)
阅读全文
0 0
- lintcode python代码 463 整数排序
- Lintcode 463 整数排序
- lintcode 463整数排序 lintcode 464整数排序II
- lintcode整数排序的完整c++代码
- (lintcode)第463题整数排序
- LintCode 第463题 整数排序
- LintCode:整数排序
- 【LintCode】整数排序II
- LintCode【入门】整数排序
- 整数排序II-lintcode
- lintcode-入门-整数排序
- LintCode-整数排序
- LintCode-整数排序 II
- 整数排序-LintCode
- LintCode 整数排序
- LintCode 整数排序 II
- LintCode 整数排序
- Lintcode整数排序
- 微信接入
- java 登陆窗口的实现
- 记录web历程
- java 学习笔记---布局管理组件
- PHP处理textarea上传的数据
- lintcode python代码 463 整数排序
- JFrame 和JPanel 的关系-区别(学习笔记)
- BAT,网易,新浪等互联网公司的业务架构及系统架构案例
- 登陆窗口实现(二)-----使用JPanel
- context-param和init-param区别
- chrome 下使用维基百科
- 关于脑裂
- Android Studio APK打包
- APK瘦身