zoukankan      html  css  js  c++  java
  • 冒泡排序、选择排序、二分查找排序

    package day04.d1.shuzu;

    import java.util.Arrays;

    /**
    * 数组算法测试
    * 冒泡排序
    * 快速选择排序
    * ...
    * @author Administrator
    *
    */
    public class ArrayArithmeticTest {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[] arr={50,40,30,35};
    selectSort(arr);

    System.out.println(Arrays.toString(arr));

    int[] arr2={50,40,30,35};
    bubbleSort(arr2);

    System.out.println(Arrays.toString(arr2));

    int[] arr3={30,2,5,3,7,1,6,4,12,56,45,33};
    Arrays.sort(arr3);
    int index=binarySearch(arr3,0,arr3.length,7);
    System.out.println("index "+index);
    }

    /**
    * 选择排序
    * @param arr
    */
    public static void selectSort(int[] arr){
    int temp=0;
    for (int i = 0; i < arr.length-1; i++) {
    for (int j = i+1; j < arr.length; j++) {
    if(arr[i]>arr[j]){
    temp=arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
    }
    }
    }
    }

    /**
    * 冒泡排序
    * @param arr
    */
    public static void bubbleSort(int[] arr){
    int temp=0;
    for (int i = 0; i < arr.length-1; i++) {
    for (int j = 0; j < arr.length-1-i; j++) {
    if(arr[j]>arr[j+1]){
    temp=arr[j];
    arr[j]=arr[j+1];
    arr[j+1]=temp;
    }
    }
    }
    }

    /**
    * 二分查找
    * @param arr
    * @param start
    * @param end
    * @param key
    */
    public static int binarySearch(int[] arr,int start,int end,int key){
    int mid=(start+end)/2;
    if(arr[mid]==key){
    return mid;
    }else if(arr[mid]>key){
    end=mid;
    binarySearch(arr,start,end,key);
    }else if(arr[mid]<key){
    start=mid;
    binarySearch(arr,start,end,key);
    }
    return 0;
    }



    }

  • 相关阅读:
    JSTL XML标签库 使用
    JSTL SQL标签库 使用
    JSTL I18N 格式标签库
    基于struts2的ajaxfileupload异步上传插件的使用
    Spring 使用注解方式进行事务管理
    vi编辑器的使用方式
    js基础知识介绍
    选择语句
    数组
    0411作业
  • 原文地址:https://www.cnblogs.com/1020182600HENG/p/6566256.html
Copyright © 2011-2022 走看看