463 整数排序
给一组整数,按照升序排序,使用选择排序,冒泡排序,插入排序或者任何 O(n2) 的排序算法。
C++代码 冒泡法
public class Solution {
/**
* @param A an integer array
* @return void
*/
public void sortIntegers(int[] A) {
// Write your code here
if(A==null || A.length<=1)
return;
int n = A.length;
for(int i=n-1;i>=0;i--){
for(int j=0;j<i;j++){
if(A[j]>A[j+1]){
swap(A,j,j+1);
}
}
}
}
public void swap(int[] A,int i,int j){
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}
python代码
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)