1.冒泡排序Bubble Sort
public class BubbleSort { public static void main(String[] args) { int[] arr = {2,5,7,1,6,4,9}; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length - 1 - i ; j++) { if(arr[j]>arr[j+1]){ int temp = arr[j+1]; arr[j+1] = arr[j]; arr[j] = temp; } } } for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]); //1245679 } } }
代码解释: 外层for循环可以当成是一个计数器:控制内层for循环的次数。
每一次外圈循环完成后会将最大元素排到最后一位,这样下一次内圈循环就不必比较相对最后两位元素了,于是内圈循环次数减少相应的数值
2.选择排序Selection Sort
public class SelectionSort { public static void main(String[] args) { int[] arr = {2,5,7,1,6,4,9}; int minIndex,temp; for (int i = 0; i < arr.length-1; i++) { minIndex = i; for (int j = i+1; j < arr.length; j++) { if(arr[j]<arr[minIndex]){ minIndex = j; } } temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]); //1245679 } } }
3.插入排序Insertion Sort
public class InsertionSort { public static void main(String[] args) { int[] arr = { 2, 5, 7, 1, 6, 4, 9 }; int preIndex, current; for (int i = 1; i < arr.length; i++) { preIndex = i - 1; current = arr[i]; while (preIndex >= 0 && arr[preIndex] > current) { arr[preIndex + 1] = arr[preIndex]; preIndex--; } arr[preIndex + 1] = current; } for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]); //1245679 } } }
4.希尔排序Shell Sort
public class ShellSort { public static void main(String[] args) { int[] arr = { 2, 5, 7, 1, 6, 4, 9 }; int temp, j; int gap = 1; while (gap < arr.length / 3) { gap = gap * 3 + 1; } for (; gap > 0; gap = (int) Math.floor(gap / 3)) { for (int i = gap; i < arr.length; i++) { temp = arr[i]; for (j = i - gap; j > 0 && arr[j] > temp; j -= gap) { arr[j + gap] = arr[j]; } arr[j + gap] = temp; } } for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); // 1245679 } } }
5.归并排序Merge Sort
后边的会陆续更新
原文地址:https://www.cnblogs.com/xuyiqing/p/8545967.html
时间: 2024-10-10 19:51:24