算法新手学习,重在联系和理解思想
选择排序
对一个数组找出最小的位置,并且把最小位置的元素放在最左边,不用管前面的了
private static void selectSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
//0 -- N-1
//1 -- N-1
//2 -- N-1
//i -- N-1 就是找最小值的位置 并且输出
for (int i = 0; i
冒泡排序
对一个数组元素两两比较把大的元素放在最右边,然后就不用管最后一位了
private static void bubbleSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
//0 -- n-1
//0 -- n-2
//0 -- n-3
//0 -- end 找出最大值放在最左边
for (int end = arr.length-1; end >= 0 ; end--) {
for (int i = 0; i arr[end]){
swap(arr, i, end);
}
}
}
}
插入排序
像斗地主我们起牌一样,每拿一个新牌就会从右向左比较,只要不比前者小就插入。保证被插入的数组本来就有序
private static void insertSort(int[] arr) {
//0 -- 1
//0 -- 2
//0 -- 3
//0 -- n-1
if (arr == null || arr.length < 2) {
return;
}
for (int end = 1; end =1 && arr[newNumIndex-1] > arr [newNumIndex]){
swap(arr, newNumIndex-1, newNumIndex);
newNumIndex--;
}
}
}
private static void insertSort2(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
for (int end = 1; end =0&& arr[pre] > arr [pre+1]; pre--) {
swap(arr, pre, pre+1);
}
}
}



