内部排序

mac2022-06-30  25

1.插入排序法

直接插入排序,像咱们打扑克一样。

package Client; import java.util.Random; public class Sort { public static void main(String []args){ int a[]=new int[10]; for(int i=0;i<a.length;i++){ a[i]=new Random().nextInt(100); } for(int i=0;i<a.length;i++){ System.out.print(a[i]+" "); if(i==0 &&i!=0){ System.out.println(); } } //直接插入法排序 sort(a,a.length); System.out.println(); for(int i=0;i<a.length;i++){ System.out.print(a[i]+" "); if(i==0 &&i!=0){ System.out.println(); } } } public static void sort(int a[], int length){ int tem=0;//待插入的值 int j=0;//初始化 for(int i=1;i<a.length;i++){ tem=a[i]; j=i-1; while(j>=0 && tem<a[j] ){ //如果待插入的数小于比较的数,则比较的数后移 a[j+1]=a[j]; j=j-1; } a[j+1]=tem; } } }

2,冒泡排序法

public static void bubblesort ( int a[]) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a.length - i-1; j++) { if (a[j] > a[j + 1]) { int tem = a[j]; a[j] = a[j + 1]; a[j + 1] = tem; } } } }

3.快速排序法

public static void quicksort ( int a[],int low ,int high) { while(low<high){ int pos=qkpass(a,low,high); quicksort(a,low,pos-1); quicksort(a,pos+1,high); } } private static int qkpass(int[] a, int low, int high) { int tem=a[low]; while(low<high){ while(low<high && a[high]>=tem){ high--; } if(low<high){ a[low]=a[high]; low++; } while(low<high && a[low]<tem){ low++; } if(low<high){ a[high]=a[low]; high--; } } a[low]=tem; return low; }

 

最新回复(0)