码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode 463 Sort Integer

时间:2016-12-24 02:09:33      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:cti   find   for   selection   lint   turn   key   while   tin   

这个是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;

}
}

LintCode 463 Sort Integer

标签:cti   find   for   selection   lint   turn   key   while   tin   

原文地址:http://www.cnblogs.com/wenchan/p/6216514.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!