public class xuanzhe { public static void main(String[] args) {
int[] a = {20,2,3,5,4,1,6,7,33,22,33,11,32,12};
xuanzheSort(a);
}
public static void xuanzheSort(int[] a){
int[] b = a;
int swap=0;
for(int i=0;i<a.length;i++){
int temp = a[i];
for(int j=1;j<b.length;j++){
if(temp>b[j]){
swap = temp;
temp = b[j];
b[j] = swap;
}
}
System.out.print(temp+" ");
}
}
}
输出的结果是 1,2,3,4,5,6,7,11,12,20,20,20,20,20
为什么从20后面就错了 额,代码哪有错额???哪位锅锅能解释下额
int[] a = {20,2,3,5,4,1,6,7,33,22,33,11,32,12};
xuanzheSort(a);
}
public static void xuanzheSort(int[] a){
int[] b = a;
int swap=0;
for(int i=0;i<a.length;i++){
int temp = a[i];
for(int j=1;j<b.length;j++){
if(temp>b[j]){
swap = temp;
temp = b[j];
b[j] = swap;
}
}
System.out.print(temp+" ");
}
}
}
输出的结果是 1,2,3,4,5,6,7,11,12,20,20,20,20,20
为什么从20后面就错了 额,代码哪有错额???哪位锅锅能解释下额
public class Test {
public static void main(String[] args) {
int[] a = { 20, 2, 3, 5, 4, 1, 6, 7, 33, 22, 33, 11, 32, 12 };
xuanzheSort(a);
} public static void xuanzheSort(int[] b) {
int swap = 0;
for (int i = 0; i < b.length; i++) {
//int temp = b[i];//症结,你只是取到值而不是引用。所以你修改的只是temp和b[j];
for (int j = i; j < b.length; j++) {
if (b[i] > b[j]) {
swap = b[i];
b[i] = b[j];
b[j] = swap;
}
}
int temp = b[i];
System.out.print(temp + " ");
}
}
}
B = [20,1,2,3,4,5,6,12,14,21,29,30]
你有俩个循环,循环i和循环j
你的i循环每进1(即i++),都会把A中的第一个数字换进B(即拿20换了1);
所以,当i进5的时候,你的B是这个样子的:
[20,20,20,20,20,20,6,7,12,14,21,29,30].
所以都没有机会查到比第一个数字大的数字了。
public class xuanzhe { public static void main(String[] args) {
int[] a = {20,2,3,5,4,1,6,7,33,22,11,32,12,55,44,43,42};
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
System.out.println();
xuanzheSort(a);
}
public static void xuanzheSort(int[] a){
/*
* int swap=0;
for(int i=0;i<a.length;i++){
int temp = a[i];
for(int j=i+1;j<a.length;j++){
if(temp>a[j]){
swap = temp;
temp = a[j];
a[j] = swap;
}
}
System.out.print(temp+" ");
}
}
**/
public static void main(String[] args) {
int[] a = { 20, 2, 3, 5, 4, 1, 6, 7, 33, 22, 33, 11, 32, 12 };
xuanzheSort(a);
} public static void xuanzheSort(int[] b) {
int swap = d0;
for (int i = 0; i < b.length; i++) {
//int temp = b[i];//症结,你只是取到值而不是引用。所以你修改的只是temp和b[j];
for (int j = i; j < b.length; j++) {
if (b[i] > b[j]) {
swap = b[i];
b[i] = b[j];
b[j] = swap;
}
}
int temp = b[i];
System.out.print(temp + " ");
}
}
}
{
public static void main(String[] args) {
int[] a = {20,2,3,5,4,1,6,7,33,22,33,11,32,12,36,69,87,98};
xuanzheSort(a); }
public static void xuanzheSort(int[] a){
int[] b=a;
for(int i=0;i<a.length;i++){
int temp=a[i];
for(int j=i+1;j<b.length;j++){
int swap=0;
if(temp>b[j]){
swap =b[j];
b[j] =temp;
temp = swap;
}
}
a[i]=temp;
}
for(int i=0;i<b.length;i++)
System.out.println(a[i]);
}
}
我都说了int temp = a[i] 只是 得到了 a[i] 的值,而非引用,所以你修改temp ,并不会修改 a[i]的值。所以我建议你直接修改a[i]。
或者
for (int i = 0; i < b.length; i++) {
int temp = b[i];
for (int j = i; j < b.length; j++) {
if (b[i] > b[j]) {
b[i] = b[j];
b[j] = temp;
}
}
这个意思就是交换了。只是你没把引用和传值搞清楚。也就是说如果,你那么用的结果是就是 b[i]不改变,把b[j]的值替换掉了,你打印下结果就知道了。