我们对三大排序的算法原理进行概括性的讲解:
首先,冒泡排序就是在每一轮的排序中,将最大值的一个劲的放在最后面。因此在每一轮的比较中,若遇见前面的数比后面的数大的情况的时候,则进行转换。
再次,讲解一下选择排序。选择排序中选择像一个钓鱼时漂在水面的鱼浮,只要有鱼上钩时则鱼浮则会向下沉,而选择排序也是这样:用一个minIndex表示在每一轮排序中选择最小的数的位置,在比较过程中若发现有比当前数还要小的数,那么我就把“鱼浮”放在你的位置(就是相当于你那个地方有鱼,我不管,我要把鱼浮放在你的那个地方),在每一轮比较完之后,我会发现一个在这一轮比较中最小的数,因此我把最小的数值和我的值进行转换。
最后,就是插入排序。插入排序就相当于斗地主起牌的时候,(我这个人有强迫症,总是将牌按照牌点顺序放好),而插入顺序也是这样,一步一个脚印进行比较,直到所有的都安排好。
一、冒泡排序
/**
* 冒泡排序
*/
public class BubbleSort {
public static void main(String[] args) {
int[] a = new int[]{0,3,5,6,4,2};
new BubbleSort().bubbleSort(a);
for (int i=0; i<a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.print("\n");
}
public void bubbleSort(int[] arr) {
if (arr==null || arr.length<2) {
return ;
}
for (int end=arr.length-1; end>0; end--) {
for (int i=0; i<end; i++) {
if (arr[i] > arr[i+1]) {
swap(arr, i, i+1);
}
}
}
}
public void swap(int[] arr, int i, int j) {
int temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
二、选择排序
/**
* 选择排序
*/
public class SelectSort {
public static void main(String[] args) {
int[] a = new int[]{0,3,5,6,4,2};
new SelectSort().selectionSort(a);
for (int i=0; i<a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.print("\n");
}
public void selectionSort(int[] arr) {
if (arr==null || arr.length<2) {
return ;
}
// 选择一个类似浮子标记,只标记当前最小的数的下标
for (int i=0; i<arr.length; i++) {
int minIndex = i;
for (int j=i+1; j<arr.length; j++) {
// if (arr[minIndex]> arr[j]) {
// minIndex = j;
// }
minIndex = arr[minIndex]> arr[j]? j: minIndex; //这里可以进行简化
// if (arr[i] > arr[j]) {
// swap(arr, i, j);
// }
}
swap(arr, i, minIndex);
}
}
public void swap(int[] arr, int i, int j) {
int temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
三、插入排序
package basic_class_1;
/**
* 插入排序
* @author luo
*
*/
public class InsertionSort {
public static void main(String[] args) {
int[] a = new int[]{0,3,5,6,4,2};
new InsertionSort().insertionSort(a);
for (int i=0; i<a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.print("\n");
}
public void insertionSort(int[] arr) {
if (arr==null || arr.length<2) {
return ;
}
//相当于插牌一样,将牌插入到合适的位置
for (int i=1; i<arr.length; i++) {
for (int j=i-1; j>=0; j--) {
if (arr[j+1] < arr[j]) {
swap(arr, j+1, j);
}
}
}
}
public void swap(int[] arr, int i, int j) {
int temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}