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;
}
}
}
}
}
插入排序二分排序冒泡排序
最新推荐文章于 2022-07-24 20:15:59 发布