With
string[] z = { "arc", "banana", "cucumber", "deer", "elephant", "fiesta", "giga", "home", "idea", "jump" };
int[] y = { 189, 178, 65, 63, 200, 1000, 10, 15, 28, 20 };
I do a bubble sort of z
ordered by y
:
for (int i=0;i<=(y.length-2);i++){
for (int j=(y.length-1); i<j;j--){
if (y[j]<y[j-1]){
int temp= y[j-1];
y[j-1]=y[j];
y[j]=temp;
String tempo=z[j-1];
z[j-1]=z[j];
tempo=z[j];
}
}
}
for (int i=y.length-1;i>0;i--){
System.out.println(z[i]);}
After the print the output of the z
is:
jump, jump, jump, idea, idea, idea, idea, home, home, home
Why does sorting delete some values of z
?
You are not using the temporary variable for the string array. With your code you save the content of z[j-1]
in tempo
, but you don't write it back to the array:
Instead of
String tempo=z[j-1];
z[j-1]=z[j];
tempo=z[j];
try this:
String tempo = z[j - 1];
z[j - 1] = z[j];
z[j] = tempo;
And in your output loop, you've got an off by one error . Use >=0
:
for (int i=y.length-1;i>=0;i--)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.