算法与数据结构-04-排序算法
冒泡排序(大小相邻比较,交换):
1 package sgq0321; 2 3 import java.util.Arrays; 4 5 public class BubbleSort { 6 7 public static void main(String[] args) { 8 BubbleSort bubbleSort = new BubbleSort(); 9 System.out.println(Arrays.toString(bubbleSort.bubble(new int[]{9, 3, 1}))); 10 } 11 12 public int[] bubble(int[] arr) { 13 for (int i = 0; i < arr.length - 1; i++) { 14 boolean flag = true; 15 for (int j = 0; j < arr.length - i - 1; j++) { 16 if (arr[j] > arr[j + 1]) { 17 flag = false; 18 int temp = arr[j + 1]; 19 arr[j + 1] = arr[j]; 20 arr[j] = temp; 21 } 22 } 23 if (flag) { 24 return arr; 25 } 26 } 27 return arr; 28 } 29 }选择排序(默认排头最小值,后续有更小值进行交换):
package sgq0321; import java.util.Arrays; public class SelectSort { public static void main(String[] args) { SelectSort bubbleSort = new SelectSort(); System.out.println(Arrays.toString(bubbleSort.select(new int[]{9, 3, 1}))); } public int[] select(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { int min = i; int minValue = arr[i]; for (int j = i; j < arr.length; j++) { if (arr[j] < minValue) { minValue = arr[j]; min = j; } } if (min == i) continue; arr[min] = arr[i]; arr[i] = minValue; } return arr; } }插入排序(原数组分前后两段,前有序后无序,后依次取值插入前合适位置):
package sgq0321; import java.util.Arrays; public class InsertSort { public static void main(String[] args) { InsertSort bubbleSort = new InsertSort(); System.out.println(Arrays.toString(bubbleSort.insert(new int[]{5,9, 3, 1}))); } public int[] insert(int[] arr) { for (int i = 1; i < arr.length; i++) { // index of the position to be inserted int insertIndex=i-1; // the value of the current index location int currentValue=arr[i]; // if currentValue < the sequence has been shot while(insertIndex>=0 && currentValue<arr[insertIndex]){ // 前面的值后移 arr[insertIndex+1]=arr[insertIndex]; insertIndex--; } arr[insertIndex+1]=currentValue; } return arr; } }快速排序
package sgq0321; import java.util.Arrays; public class QuickSort { public static void main(String[] args) { QuickSort bubbleSort = new QuickSort(); int[] ints = {8, 9, 1, 7, 2, 3, 5, 4, 6, 0}; bubbleSort.quick(ints, 0, ints.length - 1); System.out.println(Arrays.toString(ints)); } public void quick(int[] arr, int left, int right) { int l = left; int r = right; int pivot = arr[(l + r) / 2]; while (l < r) { while (arr[l]<pivot){ l++; } while (arr[r]>pivot){ r--; } if(l>r){ break; } int temp=arr[l]; arr[l]=arr[r]; arr[r]=temp; r--; l++; } if(left<r){ quick(arr,left,r); } if(l<right){ quick(arr,l,right); } } }