package com.hsm.mySort; import java.util.Random; /** * 排序 * @author steven * */ public class MySort { public static void main(String[] args) { Random rd=new Random(); int a[]=new int[100]; for(int i=0;i<100;i++){ a[i]=rd.nextInt(1000); } //bubbleSort(a); //insertSort(a); //shellSort(a); selectSort(a); } /** * 冒泡排序 * @param a */ static void bubbleSort(int [] a){ int temp=0;//臨時交換 for(int i=0;i<a.length;i++){//遍歷 boolean flag=false;//標識有沒有交換 for(int j=i+1;j<a.length;j++){ if(a[i]>a[j]){ temp=a[i]; a[i]=a[j]; a[j]=temp; flag=true; } } if(flag) break;//沒有交換元素代表已是有序的了 } for (int i : a) {//輸出排好序的元素 System.out.println(i); } } /** * 插入排序 * @param a */ static void insertSort(int [] a){ int temp=0;//臨時交換 int j=0; for(int i=1;i<a.length;i++){//遍歷 temp=a[i]; for(j=i;j>0&&a[j-1]>temp;j--){//將元素日後移 a[j]=a[j-1]; } a[j]=temp;//將元素插入到正確的位置 } for (int i : a) {//輸出排好序的元素 System.out.println(i); } } /** * 希爾排序 * @param a */ static void shellSort(int [] a){ int temp=0; int j; for(int d=a.length/2;d>0;d/=2){//間隔每次爲原來的1/2 for(int i=0;i<a.length/d;i++){//這個地方其實就是插入排序 temp=a[i]; for(j=i;j>=d&&a[j-d]>temp;j-=d){//將元素日後移 a[j]=a[j-d]; } a[j]=temp;//將元素插入到正確的位置 } } for (int i : a) {//輸出排好序的元素 System.out.println(i); } } /** * 選擇排序 * @param a */ static void selectSort(int [] a){ int temp=0;//記錄最小值的位置 int temp2=0; for(int i=0;i<a.length;i++){//遍歷 boolean flag=false;//標識有沒有交換 for(int j=i;j<a.length;j++){ if(a[j]<a[temp]){ temp=j; } } if(flag) break;//沒有交換元素代表已是有序的了 temp2=a[i]; a[i]=a[temp]; a[temp]=temp2; } for (int i : a) {//輸出排好序的元素 System.out.println(i); } } }