1 import java.util.Arrays; 2 import java.util.Random; 3 4 /** 5 * Created by Administrator on 2019/11/25. 6 */ 7 public class Application { 8 public static void main(String[] args) { 9 int[] array=new int[8]; 10 Sort sort=new Sort(); 11 fillArray(array); 12 System.out.println("快速排序前:"+ Arrays.toString(array)); 13 sort.quickSort(array,0,array.length-1); 14 System.out.println("排序后:"+ Arrays.toString(array)); 15 System.out.println("---------------------------------------"); 16 17 fillArray(array); 18 System.out.println("冒泡排序前:"+ Arrays.toString(array)); 19 sort.bubbleSort(array); 20 System.out.println("排序后:"+ Arrays.toString(array)); 21 System.out.println("---------------------------------------"); 22 23 fillArray(array); 24 System.out.println("插入排序前:"+ Arrays.toString(array)); 25 sort.insertSort(array); 26 System.out.println("排序后:"+ Arrays.toString(array)); 27 System.out.println("---------------------------------------"); 28 29 30 } 31 public static void fillArray(int[] array){ 32 Random random=new Random(); 33 for(int i=0;i<array.length;i++){ 34 array[i]=random.nextInt(50); 35 } 36 } 37 public static class Sort{ 38 //冒泡排序 39 private void bubbleSort(int[] nums){ 40 int temp; 41 for(int i=1;i<nums.length;i++){ 42 for(int j=0;j<nums.length-i;j++){ 43 if(nums[j]>nums[j+1]){ 44 temp=nums[j]; 45 nums[j]=nums[j+1]; 46 nums[j+1]=temp; 47 } 48 } 49 } 50 } 51 //选择排序 52 private void selectSort(int[] nums) { 53 int index; 54 int temp; 55 for (int i = 0; i < nums.length - 1; i++) { 56 index = i; 57 for (int j = i + 1; j < nums.length; j++) { 58 if (nums[j] < nums[index]) { 59 index = j; 60 } 61 } 62 if (index != i) { 63 temp = nums[i]; 64 nums[i] = nums[index]; 65 nums[index] = temp; 66 } 67 } 68 } 69 //插入排序 70 private void insertSort(int[] nums){ 71 int i,j,k; 72 for(i=1;i<nums.length;i++){ 73 k=nums[i]; 74 j=i-1; 75 while(j>=0&&nums[j]>k){ 76 nums[j+1]=nums[j]; 77 j--; 78 } 79 nums[j+1]=k; 80 } 81 } 82 //快速排序 83 private void quickSort(int[] array,int low,int high){ 84 85 int i,j,pivot; 86 pivot=array[low]; 87 i=low; 88 j=high; 89 while (i<j){ 90 while(i<j&&array[j]>=pivot){ 91 j--; 92 } 93 array[i]=array[j]; 94 while(i<j&&array[i]<=pivot){ 95 i++; 96 } 97 array[j]=array[i]; 98 } 99 array[i]=pivot; 100 if(low<i){ 101 quickSort(array,low,i-1); 102 } 103 if(high>i){ 104 quickSort(array,i+1,high); 105 } 106 107 108 } 109 } 110 111 }
今天手写复习一下常用的几种排序