1package com.hsm.mySort; 2 3import java.util.Random; 4 5/** 6 * 排序 7 * @author steven 8 * 9 */ 10public class MySort { 11 public static void main(String[] args) { 12 Random rd=new Random(); 13 int a[]=new int[100]; 14 for(int i=0;i<100;i++){ 15 a[i]=rd.nextInt(1000); 16 } 17 //bubbleSort(a); 18 //insertSort(a); 19 //shellSort(a); 20 selectSort(a); 21 } 22 /** 23 * 冒泡排序 24 * @param a 25 */ 26 static void bubbleSort(int [] a){ 27 int temp=0;//临时交换 28 for(int i=0;i<a.length;i++){//遍历 29 boolean flag=false;//标识有没有交换 30 for(int j=i+1;j<a.length;j++){ 31 if(a[i]>a[j]){ 32 temp=a[i]; 33 a[i]=a[j]; 34 a[j]=temp; 35 flag=true; 36 } 37 } 38 if(flag) break;//没有交换元素表明已经是有序的了 39 } 40 for (int i : a) {//输出排好序的元素 41 System.out.println(i); 42 } 43 } 44 /** 45 * 插入排序 46 * @param a 47 */ 48 static void insertSort(int [] a){ 49 int temp=0;//临时交换 50 int j=0; 51 for(int i=1;i<a.length;i++){//遍历 52 temp=a[i]; 53 for(j=i;j>0&&a[j-1]>temp;j--){//将元素往后移 54 a[j]=a[j-1]; 55 } 56 a[j]=temp;//将元素插入到正确的位置 57 } 58 for (int i : a) {//输出排好序的元素 59 System.out.println(i); 60 } 61 } 62 /** 63 * 希尔排序 64 * @param a 65 */ 66 static void shellSort(int [] a){ 67 int temp=0; 68 int j; 69 for(int d=a.length/2;d>0;d/=2){//间隔每次为原来的1/2 70 for(int i=0;i<a.length/d;i++){//这个地方其实就是插入排序 71 temp=a[i]; 72 for(j=i;j>=d&&a[j-d]>temp;j-=d){//将元素往后移 73 a[j]=a[j-d]; 74 } 75 a[j]=temp;//将元素插入到正确的位置 76 } 77 } 78 for (int i : a) {//输出排好序的元素 79 System.out.println(i); 80 } 81 } 82 /** 83 * 选择排序 84 * @param a 85 */ 86 static void selectSort(int [] a){ 87 int temp=0;//记录最小值的位置 88 int temp2=0; 89 for(int i=0;i<a.length;i++){//遍历 90 boolean flag=false;//标识有没有交换 91 for(int j=i;j<a.length;j++){ 92 if(a[j]<a[temp]){ 93 temp=j; 94 } 95 } 96 if(flag) break;//没有交换元素表明已经是有序的了 97 temp2=a[i]; 98 a[i]=a[temp]; 99 a[temp]=temp2; 100 } 101 for (int i : a) {//输出排好序的元素 102 System.out.println(i); 103 } 104 } 105}
java 实现排序
Wesley13
2021-10-11
1142 1 0
点赞
收藏
评论区
加载中...