描述
给一组整数,按照升序排序,使用选择排序,冒泡排序,插入排序或者任何 O(n2) 的排序算法。
样例
样例 1:
输入: [3, 2, 1, 4, 5]
输出: [1, 2, 3, 4, 5]
样例解释:
返回排序后的数组。
样例 2:
输入: [1, 1, 2, 1, 1]
输出: [1, 1, 1, 1, 2]
样例解释:
返回排好序的数组。
1.冒泡排序法代码实现
public class Solution {
/**
* @param A: an integer array
* @return: nothing
*/
public void sortIntegers(int[] A) {
// write your code here
int temp = 0;
for (int i = 0; i < A.length - 1; i++) {
for (int j = 0; j < A.length - 1 - i; j++) {
if (A[j] > A[j + 1]){
temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
}
}
}
}
}
2.选择排序法实现
public class Solution {
/**
* @param A: an integer array
* @return: nothing
*/
public void sortIntegers(int[] A) {
// write your code here
int temp = 0;
for (int i = 0; i < A.length - 1; i++) {
int min = A[i];
int index = i;
for (int j = i + 1; j < A.length; j++) {
if (A[j] < min){
min = A[j];
index = j;
}
}
temp = A[i];
A[i] = min;
A[index] = temp;
}
}
}
3.插入排序法实现
public class Solution {
/**
* @param A: an integer array
* @return: nothing
*/
public void sortIntegers(int[] A) {
// write your code here
for (int i = 1; i < A.length; i++) {
int insertVal = A[i];
int insertIndex = i - 1;
while (insertIndex >= 0 && insertVal < A[insertIndex]){
A[insertIndex + 1] = A[insertIndex];
insertIndex--;
}
A[insertIndex + 1] = insertVal;
}
}
}