常见部分排序

来源:互联网 发布:linux 添加自定义命令 编辑:程序博客网 时间:2024/06/05 20:39
1冒泡排序
public void maopao(int b[]){if (b==null || b.length<=0) {return ;}for (int i = 1; i < b.length; i++) {for (int j = 0; j< b.length-1; j++) {if (b[j]>b[j+1]) {int temp;temp =b[j];b[j] =b[j+1];b[j+1] = temp;}}}}

2.选择排序

public void xuanze(int b[]){if (b==null || b.length<=0) {return ;}for(int i=0; i<b.length; i++){            int min = b[i];             int temp;            int index = i;            for(int j=i+1;j<b.length;j++){                if(b[j] < min){                     min = b[j];                     index = j;                }                   }                       temp = b[i];             b[i] = min;            b[index]= temp;}       }
3.插入排序

public void  insertion_sort(int b[]){if (b==null || b.length<=0) {return ;}for (int i = 1; i < b.length; i++)         {             if (b[i - 1] > b[i])             {                 int temp = b[i];                 int j = i;                 while (j > 0 && b[j - 1] > temp)                 {                     b[j] = b[j - 1];                     j--;                 }                 b[j] = temp;             }         }}
4.快速排序

public class Test {public static void main(String []args){        System.out.println("Hello World");        int[] a = {12,20,5,16,15,1,30,45,23,9};        int start = 0;        int end = a.length-1;        Test test = new Test();        test. sort(a,start,end);        for(int i = 0; i<a.length; i++){             System.out.println(a[i]);         }             }          public void sort(int[] a,int low,int high){         int start = low;         int end = high;         int key = a[low];                           while(end>start){             //从后往前比较             while(end>start&&a[end]>=key)  //如果没有比关键值小的,比较下一个,直到有比关键值小的交换位置,然后又从前往后比较                 end--;             if(a[end]<=key){                 int temp = a[end];                 a[end] = a[start];                 a[start] = temp;             }             //从前往后比较             while(end>start&&a[start]<=key)//如果没有比关键值大的,比较下一个,直到有比关键值大的交换位置                start++;             if(a[start]>=key){                 int temp = a[start];                 a[start] = a[end];                 a[end] = temp;             }         //此时第一次循环比较结束,关键值的位置已经确定了。左边的值都比关键值小,右边的值都比关键值大,但是两边的顺序还有可能是不一样的,进行下面的递归调用         }         //递归         if(start>low) sort(a,low,start-1);//左边序列。第一个索引位置到关键值索引-1         if(end<high) sort(a,end+1,high);//右边序列。从关键值索引+1到最后一个     }}



 

原创粉丝点击