插入排序二分排序冒泡排序


import java.util.Scanner;
public class BinarySorted{
 public static void main(String args[]){
  Scanner sc = new Scanner(System.in);
  System.out.println("请问你要输入几个数字");
  int n = sc.nextInt();
  int[] array = new int[n];
  StringBuilder sb = new StringBuilder();
  sb.append("[");
  System.out.println("请分别输入数组");
  for(int i = 0;i < n;i ++){
   array[i] = sc.nextInt();
   sb.append(array[i]);
   sb.append(",");
  }
  sc.close();
  sb.deleteCharAt(sb.length() - 1);
  sb.append("]");

  System.out.println("原始数组为"+sb.toString());  
  int[] array1 = array;
  System.out.println("插入排序法如下");
  insertSorted(array1);
  for(int i = 0;i < array1.length;i ++){
   System.out.println(array1[i]);
  }

  int[] array2 = array;
  System.out.println("冒泡排序如下");
  bubbleSorted(array2);
  for(int i = 0;i < array2.length;i ++){
   System.out.println(array2[i]);
  }
  int[] array3 = array;
  System.out.println("二分排序法如下");
  binarySorted(array3);
  for(int i = 0;i < array3.length;i ++){
   System.out.println(array3[i]);
  }

 }
 //二分排序法
 public static void binarySorted(int[] array){
  for(int i = 1;i < array.length;i ++){
   int low = 0;
   int high = i - 1;
   while(low < high){
    int mid = (low + high) / 2;
    if(array[i] > array[mid])
     low = mid + 1;
    else if(high > 0)
     high = mid - 1;
   }
   if(array[(low + high) / 2] > array[i]){
    int temp = array[i];
    for(int j = i;j > (low + high) / 2;j --){
     array[j] = array[j - 1];
    }
    array[(low + high) / 2] = temp;
   }
  }

 }
 //插入排序法
 public static void insertSorted(int[] array){
  for(int i = 1;i < array.length;i ++){
   for(int j = i - 1;j >= 0;j --){
    if(array[j + 1] < array[j]){
     int temp = array[j + 1];
     array[j + 1] = array[j];
     array[j] = temp;
    }
   }
  }
 }

 //冒泡排序法
 public static void bubbleSorted(int[] array){
  for(int i = 0;i < array.length - 1;i ++){
   for(int j = 0;j < array.length - i - 1;j ++){
    if(array[j] > array[j + 1]){
     int temp = array[j];
     array[j] = array[j + 1];
     array[j + 1] = temp;
    }
   }
  }
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值