二分法排序

代码:

package test;

import java.util.Scanner;

public class 二分排序{
	public static void main(String[] args){
		Scanner in = new Scanner(System.in);
		System.out.print("Please input the count of numbers:");
		int n,temp,low,high,mid;
		n = in.nextInt();
		int[] p = new int[n];		
		System.out.print("Please input numbers:");
		for(int i = 0;i<n;i++)
			p[i] = in.nextInt();
		for(int i=1;i<n;i++){
		  temp = p[i];
		  low = 0;
		  high = i-1;
		  mid = -1;
		  while(low <= high){			  
		  mid = (low+high)/2;
		  if(temp>p[mid])
			high = mid -1;
		  else
		  low = mid + 1;
	  }
		  for(int t = i-1;t>=low;t--){
			p[t+1] = p[t];
		  }
		  p[low]=temp;
		}
		System.out.print("After BinarySorting,the result is that:");
		for(int i=0;i<n;i++){
		if(i<=n-2)
		System.out.print(p[i]+" ");
		else
		System.out.print(p[i]);
	  }
	}
}

图片:

猜你喜欢

转载自blog.csdn.net/Tjhfsghbjknjdy/article/details/85013102