Java交换排序

来源:互联网 发布:东方卫视网络电视台 编辑:程序博客网 时间:2024/05/18 22:43

交换排序:
1.冒泡排序
2.快速排序

1>冒泡排序

基本思想:每步将一个待排序的记录,按其顺序码大小插入到前面已经排序的字序列的合适位置,直到全部插入排序完为止。

public class BubbleSort {    public static void main(String args[]) {        int[] a = {2,31,3,43,45,6,0,21,1};        System.out.print("排序前: ");           for(int i=0; i<a.length; i++) {               System.out.print(a[i] + " ");           }           System.out.println();   //换行           //冒泡排序           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 temp = a[j];                       a[j] = a[j+1];                       a[j+1] = temp;                   }               }           }           System.out.print("排序后: ");           for(int i=0; i<a.length; i++) {               System.out.print(a[i] + " ");           }    }}

结果为:
排序前: 2 31 3 43 45 6 0 21 1
排序后: 0 1 2 3 6 21 31 43 45

2>快速排序

基本思想:选择一个基准元素,通常选择第一个元素或者最后一个元素,通过一趟扫描,将待排序列分成两部分,一部分比基准元素小,一部分大于等于基准元素,此时基准元素在其排好序后的正确位置,然后再用同样的方法递归地排序划分的两部分。

public class QuickSort {    public static void main(String args[]) {        int[] a = {2,10,8,5,3,91,20,35};        System.out.print("排序前: ");           for(int i=0; i<a.length; i++) {               System.out.print(a[i] + " ");           }           System.out.println();  //换行           //快速排序           quick(a);           System.out.print("排序后:");              for(int i=0; i<a.length; i++) {                  System.out.print(a[i] + " ");              }    }    private static void quick(int[] a) {        if(a.length>0) {            quickSort(a,0,a.length-1);        }    }    private static void quickSort(int[] a, int low, int high) {        //防止堆栈溢出异常        if(low < high) {            int middle = getMiddle(a,low,high);            quickSort(a,0,middle-1);            quickSort(a,middle+1,high);        }    }    private static int getMiddle(int[] a, int low, int high) {        // TODO Auto-generated method stub        int temp = a[low];   //基准元素        //找到比基准元素小的元素位置        while(low < high) {            while(low < high && a[high] >= temp) {                high--;            }            a[low] = a[high];            while(low < high && a[low] <= temp) {                low++;            }            a[high] = a[low];        }        a[low] = temp;        return low;    }}

结果为:
排序前: 2 10 8 5 3 91 20 35
排序后:2 3 5 8 10 20 35 91

原创粉丝点击