日期:2014-05-20  浏览次数:20754 次

双数组冒泡排序问题,请各位帮忙解决!!!
有两个数组,第二个数组里的值要根据第一个数组的冒泡排序结果来排序,需求如下:
========================================================================================
String[] aStrings = {"0002","0001","0003","0008","0005","0006"};
String[] bStrings = {"a","v","f","r","b","k"};

  要想得到数组值为{"v","a","f","b","k","r"}
========================================================================================
这是我写的代码:
static void sortValuesByKey(String[] a,String[] b){

for (int i = 0; i < a.length; i++) {

for (int j = 0; j < a.length - i -1; j++) {

if (a[j].compareToIgnoreCase(a[j+1]) > 0) {

String tmp = b[j];
b[j] = b[j+1];
b[j+1] = tmp;

}
}

}
for (int k = 0; k < b.length; k++) {
System.out.println(b[k]);
}
}

但是结果不对,打印出来是
v
a
f
r
b
k


请大家帮忙,谢谢!!!!!!

------解决方案--------------------
Java code

    static void sortValuesByKey(String[] a,String[] b)
    {
        for(int i=a.length-1;i>=1;i--)
        {
            for(int j=0;j<i;j++)
            {
                if (a[j].compareToIgnoreCase(a[j+1]) > 0)
                {
                    String tmp = a[j];
                    a[j] = a[j+1];
                    a[j+1] = tmp;
    
                    String tmpB = b[j];
                    b[j] = b[j+1];
                    b[j+1] = tmpB;
                }
            }
        }
        for (int k = 0; k < b.length; k++)
               {
            System.out.println(b[k]);
        }
    }

------解决方案--------------------
我这个用的是jdk1.4,没有泛型,你可以改下
Java code

public static void sort(String[] a,String[] b){
  Map map=new HashMap();
  for(int i=0;i<a.length;i++){
     map.put(a[i],new Integer(i));
  }
  for(int i=0;i<a.length;i++){
    for(int j=0;j<a.length-i-1;j++){
       if(a[j].compareToIgnoreCase(a[j+1])>0){
          String tmp=a[j+1];
          a[j+1]=a[j];
          a[j]=tmp;
       }
    }
  }
  System.out.println("before-----");
  for(int i=0;i<b.length;i++){
     System.out.print(b[i]+" ");
  }
  System.out.println();
  System.out.println("after-----");
  for(int i=0;i<b.length;i++){
     System.out.print(b[Integer.parseInt(map.get(a[i]).toString())]+" ");
  }
}

public static void main(String[] args){
   String[] a={"0002","0001","0003","0008","0005","0006"};
   String[] b={"a","v","f","r","b","k"};
   Test.sort(a,b);
}