LintCode 463 Sort Integer

时间:2023-03-09 06:42:52
LintCode 463 Sort Integer

这个是O(n2)的排序的总结

/* bubble sort */
public static void sortIntegers(int[] A) {
// Write your code here
int len = A.length;

if (len == 0) return;

for (int j = 0; j < len; ++j) {
for (int i = 0; i < len-1-j; ++i) { // len-1-j
if (A[i] > A[i+1]) {
int temp = A[i];
A[i] = A[i+1];
A[i+1] = temp;
}
}
}
}

/* selection sort */
public static void sortIntegers(int[] A) {

for (int i = 0; i < A.length-1; i++){
int index = i;

for (int j = i+1; j < A.length; j++){
if (A[index] > A[j]) index=j; // find the smallest
}
// then swap
int smaller = A[index];
A[index] = A[i];
A[i] = smaller;
}
}

/* insertion sort */
public static void sortIntegers(int[] A) {
int n = A.length;
for (int i = 1; i < n; i++) {
int key = A[i]; // boundary

int j = i - 1; // another pointer
while ((j > -1) && (A[j] > key)) {
A[j + 1] = A[j];
j--;
}
A[j + 1] = key;

}
}