zoukankan      html  css  js  c++  java
  • 重温经典之排序 java实现

    重新写一遍,都忘记了!

    No.1  快排

     1 public class FastSort {
     2     public static void main(String[] args)throws Exception{
     3         int[] a = {10, 1, 2, 3, 7, 3, 8, 5, 6, 4};
     4         FastSort b1 = new FastSort();
     5         b1.sort(a,0,a.length-1);
     6     }
     7     void sort(int[] a ,int l ,int r)throws Exception{
     8         int i,j,t,temp;
     9         i = l ;
    10         j = r ;
    11         temp = a[l];
    12         if(l>r){
    13             return;
    14         }
    15         while (i!=j){
    16             while(i<j && a[j]>=temp){
    17                 j--;
    18             }
    19             while(i<j && a[i]<=temp){
    20                 i++;
    21             }
    22             if(i<j){
    23                 t = a[i];
    24                 a[i] = a[j];
    25                 a[j] = t ;
    26             }
    27         }
    28         a[l] = a[i];
    29         a[i] = temp;
    30         System.out.print("/");
    31         for(int h=0;h<a.length;h++){
    32             System.out.print(a[h]+" ");
    33         }
    34         sort(a , l , i-1);
    35         sort(a , i+1 , r);
    36     }
    37 }

    No.2 冒泡排序

     1 public class Bubblesort {
     2     public static void main(String []args){
     3         int []a = {3,5,72,3,8,90};
     4         sort(a);
     5     }
     6     public static void sort(int []a){
     7         int temp ;
     8         for(int i = a.length -1 ; i > 0 ; i--){
     9             for(int j = 0 ; j < i ; j++){
    10                 if(a[j+1] < a[j]){
    11                     temp = a[j+1];
    12                     a[j+1] = a[j];
    13                     a[j] = temp;
    14                 }
    15             }
    16         }
    17         for(int k = 0 ;k<a.length;k++){
    18             System.out.print(a[k]+",");
    19         }
    20     }
    21 }

    No.3 插入排序

     1 public class Insertsort {
     2     public static void main(String[] args){
     3         int []a = {3,4,4,2,5,4,6,3,2};
     4         sort(a);
     5     }
     6     static void sort(int[] a){
     7         for(int i = 1 ; i < a.length ; i++){
     8             for(int j = i ; j > 0 ; j--){
     9                 if(a[j]<a[j-1]){
    10                     int temp = a[j];
    11                     a[j] = a[j-1];
    12                     a[j-1] = temp;
    13                 }
    14             }
    15         }
    16         for(int k = 0;k<a.length;k++)
    17             System.out.print(a[k]+" ");
    18     }
    19 }
  • 相关阅读:
    20170926-构建之法:现代软件工程-阅读笔记
    我的swift的ui标签
    内存管理:内存泄漏和空悬指针
    闭包
    泛型,修饰符和异常处理
    类型转换,接口和扩展
    初始化2
    类的继承和初始化1
    枚举与可选值
    swift中的类和结构
  • 原文地址:https://www.cnblogs.com/sumbud/p/4851740.html
Copyright © 2011-2022 走看看