• 数组排序


     1 public class ccc {
     2     public void testSort1(int[] a){//选择排序
     3         int length = a.length;
     4 
     5         for(int i = 0;i<length-1;i++){
     6             int temp = a[i];
     7             int pos=i;
     8             for(int j =i+1;j<length;j++){
     9                 if(a[j]<temp){
    10                     temp = a[j];//得到这趟最小
    11                     pos = j;//这趟最小的索引
    12                 }
    13             }
    14             a[pos]= a[i];//元素赋值交换
    15             a[i] = temp;
    16         }
    17 //        System.out.println(Arrays.toString(a));
    18     }
    19 
    20     public void testSort2(int[] a){//冒泡排序
    21         int length = a.length;
    22 
    23         for(int i = 0;i<length-1;i++){
    24 
    25             for(int j = 0;j<length-i-1;j++){
    26              if(a[j+1]<a[j]){ //相邻的交换 确定出最后一个是最大的
    27                  int temp = a[j];
    28                  a[j] = a[j+1];
    29                  a[j+1] = temp;
    30              }
    31             }
    32         }
    33 //        System.out.println(Arrays.toString(a));
    34     }
    35 
    36     public void testSort3(int[] a,int l, int r){//快速排序
    37 
    38         if(l<r){
    39             int i =l,j=r,temp=a[l];
    40 
    41             while(i<j){
    42                 while(i<j && a[j]>temp){//后面
    43                     j--;
    44                 }
    45                 if(i<j){
    46                     a[i++] = a[j];//交换到1上 然后i还变成2
    47                 }
    48 
    49                 while(i<j && a[i]<temp){//前面
    50                     i++;
    51                 }
    52                 if(i<j){
    53                     a[j--] = a[i];
    54                 }
    55             }
    56 
    57             a[i] = temp;//此时必是i==j
    58             testSort3(a,l,i-1);//分治左边
    59             testSort3(a,i+1,r);//分治右边
    60         }
    61 
    62 
    63     }
    64 
    65     public static void main(String[] args) {
    66          ccc c = new ccc();
    67          int[] a = {2,6,3,1,5};
    68 //       c.testSort1(a);
    69 //       c.testSort2(a);
    70        c.testSort3(a,0,4);
    71         System.out.println(Arrays.toString(a));
    72     }
    73 }

     安利小樊同学的笔记

  • 相关阅读:
    第八次作业
    设计一款给爸爸妈妈用的手机
    第五次作业
    第四次作业(项目分析)
    第二次作业(个人项目实践)
    即时通讯软件的发展演变
    C++用法的学习心得
    JavaScript(变量、作用域和内存问题)
    一、Java和JavaScript
    使用Hyper-V创建虚拟机
  • 原文地址:https://www.cnblogs.com/gezi1007/p/13210933.html
Copyright © 2020-2023  润新知