- Sort Integers
Given an integer array, sort it in ascending order. Use selection sort, bubble sort, insertion sort or any O(n2) algorithm.
Example
Given [3, 2, 1, 4, 5], return [1, 2, 3, 4, 5].
选择排序:
public void sortIntegers(int[] A) {
for(int i = 0; i <A.length; i++){
int minIndex = i;
for(int j = i; j < A.length; j++){
if(A[j] < A[minIndex]){
minIndex = j;
}
}
int temp = A[i];
A[i] = A[minIndex];
A[minIndex] = temp;
}
}
冒泡排序:要注意如果有一轮没有进行元素交换,说明已经排好序了
public void sortIntegers(int[] A) {
while(true){
boolean exchange = false;
for(int i = 0; i < A.length - 1; i++){
if(A[i] > A[i+1]){
int temp = A[i];
A[i] = A[i+1];
A[i+1] = temp;
exchange = true;
}
}
if(!exchange) break;
}
}
插入排序:
public void sortIntegers(int[] A) {
for(int i = 0; i < A.length; i++){
int newVal = A[i];
int j = i - 1;
while(j >= 0 && A[j] > newVal){
A[j+1] = A[j];
j--;
}
A[j + 1] = newVal;
}
}