【发布时间】:2015-01-29 14:18:26
【问题描述】:
我是 java 的初学者,我一直在尝试执行插入排序,然后是二进制搜索。我已经使用随机不同的值执行了插入排序,我必须执行二进制搜索。我可以单独执行二进制搜索技术,但是如何使用特定值执行插入排序,然后使用插入排序中使用的相同值执行二进制搜索?
插入排序:
enter code here
/*
* To change this license header, choose License Headers in Project
Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package insertsort;
import java.util.Arrays;
/**
*
* @author Sriram
*/
public class InsertSort {
public static void main(String[] args) {
int A[] = new int[1000];
populateArray(A);
System.out.println("Before Sorting: ");
printArray(A);
// sort the array
insertSort(A);
System.out.println("\nAfter Sorting: ");
printArray(A);
}
/**
* This method will sort the integer array using insertion sort algorithm
*
* @param arr
*/
private static void insertSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int valueToSort = arr[i];
int j = i;
while (j > 0 && arr[j - 1] > valueToSort) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = valueToSort;
}
}
public static void printArray(int[] B) {
System.out.println(Arrays.toString(B));
}
public static void populateArray(int[] B) {
for (int i = 0; i < B.length; i++) {
B[i] = (int) (Math.random() * 1000);
}
}
}
我已经分别进行了二分查找,如下:
enter code here
package binaryinsertionsort;
import java.util.Random;
/**
*
* @author Sriram
*/
public class Binaryinsertionsort {
public static void sort(int a[],int n){
for (int i=0;i<n;++i){
int cnt;
int temp=a[i];
int left=0;
int right=i;
while (left<right){
int middle=(left+right)/2;
if (temp>=a[middle])
left=middle+1;
else
right=middle;
}
for (int j=i;j>left;--j){
swap(a,j-1,j);
}
}
}
public static void main(String[] args){
int a[]=new int[]{10,5,3,696,466,35,39,294,39,59,-21,45};
sort(a,a.length);
for (int i=0;i<a.length;i++){
System.out.println(a[i]);
}
}
public static void swap(int a[],int i,int j){
int k=a[i];
a[i]=a[j];
a[j]=k;
}
}
【问题讨论】:
-
代码太多,哪里有问题?
-
感谢您的回复,我只是发布了所有内容,以免造成混乱..我可以单独进行二进制搜索,我的问题是如何在插入排序技术中执行二进制搜索!!跨度>
-
您的搜索代码在哪里?你如何将它与这个集成?
标签: java algorithm sorting binary-search insertion-sort