public class Test {
public static void main(String[] args) {
int[] a = {4,3,8,7,9,5,1,2,6};
System.out.print("数组原型为: ");
//输出原来的数组a
for(int i=0;i<a.length;i++) {
System.out.print(a[i]+" ");
} System.out.println();
//把原来的数组用冒泡法新重对数组a从小到大排列输出
BubbleSort bubblesort = new BubbleSort(a);
System.out.println();
//用二分法在从小到到排列的数组a中,找到“1”这个数字的位置
SelectSearch selectsearch = new SelectSearch();
System.out.print("1在数组中是第几位?");
selectsearch.search(a,1);
}
}//定义冒泡法类,来把数组从小到大排列,输出。
class BubbleSort {
BubbleSort(int[] a){
System.out.print("数组从小到大排列为: ");
for(int i=0;i<a.length;i++) {
for(int j=a.length-1; j>i;j--) {
if(a[j]<a[j-1]) {
int temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
}
System.out.print(a[i]+" ");
}
}
}
//定义二分法的一个类。在前面经过冒泡法得到的从小到到排列的数组中,得到某个数的位置。
class SelectSearch {
public int search(int[] a,int num){
int m; //定义数组中间点
int startpos = 0; //定义起点
int endpos = a.length; //定义终点
m = (startpos + endpos)/2; //实现中间点的算法
while(startpos<=endpos) {
if(a[m]==num){
return m;
}
else if(a[m]<num) {
startpos = m++;
}
else {
endpos = m--;
}
}
return -1;
}
}
这个代码不知道错在哪里。编译通过了,然后运行的时候只输出:数的原型为:4 3 8 7 9 5 1 2 6
数组从小到大排列为:1 2 3 4 5 6 7 8 9
1在数组中是第几位? (这里不输出1的位置,什么都不打印)
不知道为什么,希望大家帮我看看。谢谢
public static void main(String[] args) {
int[] a = {4,3,8,7,9,5,1,2,6};
System.out.print("数组原型为: ");
//输出原来的数组a
for(int i=0;i<a.length;i++) {
System.out.print(a[i]+" ");
} System.out.println();
//把原来的数组用冒泡法新重对数组a从小到大排列输出
BubbleSort bubblesort = new BubbleSort(a);
System.out.println();
//用二分法在从小到到排列的数组a中,找到“1”这个数字的位置
SelectSearch selectsearch = new SelectSearch();
System.out.print("1在数组中是第几位?");
selectsearch.search(a,1);
}
}//定义冒泡法类,来把数组从小到大排列,输出。
class BubbleSort {
BubbleSort(int[] a){
System.out.print("数组从小到大排列为: ");
for(int i=0;i<a.length;i++) {
for(int j=a.length-1; j>i;j--) {
if(a[j]<a[j-1]) {
int temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
}
System.out.print(a[i]+" ");
}
}
}
//定义二分法的一个类。在前面经过冒泡法得到的从小到到排列的数组中,得到某个数的位置。
class SelectSearch {
public int search(int[] a,int num){
int m; //定义数组中间点
int startpos = 0; //定义起点
int endpos = a.length; //定义终点
m = (startpos + endpos)/2; //实现中间点的算法
while(startpos<=endpos) {
if(a[m]==num){
return m;
}
else if(a[m]<num) {
startpos = m++;
}
else {
endpos = m--;
}
}
return -1;
}
}
这个代码不知道错在哪里。编译通过了,然后运行的时候只输出:数的原型为:4 3 8 7 9 5 1 2 6
数组从小到大排列为:1 2 3 4 5 6 7 8 9
1在数组中是第几位? (这里不输出1的位置,什么都不打印)
不知道为什么,希望大家帮我看看。谢谢
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货