[英]Why does my bubble sort method not work?
Sorry I am still learning programming. 对不起,我还在学习编程。 Java just stops and seems to be processing something. Java只是停止并且似乎正在处理某些东西。 It says "Building java application Javaapplication2" then just sits there doing nothing. 它说“正在构建Java应用程序Javaapplication2”,然后坐在那里什么也不做。 What have a I done to cause this ? 我做了什么导致了这个?
package javaapplication2;
public class JavaApplication2 {
public static void main(String[] args) {
int a [] = {1,2,3};
int c [] = Sortarray.sortlowhigh(a);
int i = 0;
while (i<c.length){
System.out.println("array is" + c[i]);
i++;
}
}
}
package javaapplication2;
public class Sortarray {
public static int[] sortlowhigh(int a[])
{
int i = 0;
int j = 0;
while(j<a.length){
while(i<a.length){
if (a[i]>a[i+1]){
/* store low value in temp*/
int temp = a[i+1];
/* assign low value to be the higher value*/
a[i+1] = a[i];
/* assign the old higher value to be the lower value stored in temp*/
a[i]=temp;
}
j++;
}
}
return a;
}
}
My code is above. 我的代码在上面。 A while ago I wrote a sort and remove duplicates method now I want to put them into a class but I am doing something wrong. 前一阵子我写了一个排序并删除重复项的方法,现在我想把它们放到一个类中,但是我做错了什么。 Please help. 请帮忙。 Thanks. 谢谢。
在sortlowhigh while循环中,您有i,i <a.lenght是第二个循环的条件,它将一直持续到i> = a.length,但我从未更改,它始终保持为0。
/*change your code as given*/
public static int[] sortlowhigh(int a[]){
int i = 0;
int j = 0; int temp=0;
while(j<(a.length-1))
{
i=0;
while(i<a.length-j-1)
{
if(a[i]>a[i+1])/* For descending order use < */
{
temp = a[i];
a[i]=a[i+1];
a[i+1] = temp;
}
i++;
}
j++;
}
return a;
}
I try your code and I can see that you have a infinite loop in the class Sortarray. 我尝试了您的代码,发现在Sortarray类中存在无限循环。 The variable i is never increased. 变量i从不增加。 Try this code: 试试这个代码:
public static int[] sortlowhigh(int a[])
{
int i = 0;
int j = 0;
int temp;
while(j< (a.length -1) ){
i = 0;
while(i< (a.length - j - 1)){
if (a[i] > a[i+1]){
/* store low value in temp*/
temp = a[i];
/* assign low value to be the higher value*/
a[i] = a[i+1];
/* assign the old higher value to be the lower value stored in temp*/
a[i+1]=temp;
}
i++;
}
j++;
}
return a;
}
you should reset the value of i, when the value of j is incremented. 当j的值增加时,应重置i的值。 The array is of size 3. but the value of i is already 3. so it gets garbage value in a[i+1]. 该数组的大小为3。但是i的值已经为3。因此它在a [i + 1]中获得垃圾值。 Hope this helps. 希望这可以帮助。 I haven't tried the code. 我没有尝试过代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.