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

数组排序的问题
下面程序实现冒泡排序,最后输出3 8 8 12 37 59 132 352 1236 3400
我想最后不仅输出排序好的数据,还想输出数据在数组中的本来的位置,比如3400在原数组中位置为7,应该怎么改?? 
public class SortDemo {
  public SortDemo() {
  }
  public static void main(String[] args) {
  SortDemo sortDemo1 = new SortDemo();
  //初始化变量
  int[] arrayofInts={12,8,3,59,132,1236,3400,8,352,37};
  //循环整个数组
  for(int i=arrayofInts.length; --i>=0;){
  //循环每个数字
  for(int j=0;j<i;j++){
  if(arrayofInts[j]>arrayofInts[j+1]){
  int temp=arrayofInts[j];
  arrayofInts[j]=arrayofInts[j+1];
  arrayofInts[j+1]=temp;
  }
  }
  }
  //循环整个数组
  for(int i=0;i<arrayofInts.length;i++){
  System.out.println("arrayofInts["+i+"]="+arrayofInts[i]);

  }

  }

}


------解决方案--------------------
你用相关数组。
------解决方案--------------------
如果你的数组中没有重复数据的话,可以通过加一个Map来实现。

public static void main(String[] args) {
// 初始化变量
int[] arrayofInts = { 12, 8, 3, 59, 132, 1236, 3400, 8, 352, 37 };

Map<Integer, Integer> position = new HashMap<Integer, Integer>();
for (int i = 0; i < arrayofInts.length; i++) {
position.put(arrayofInts[i], i);
}

// 循环整个数组
for (int i = arrayofInts.length; --i >= 0;) {
// 循环每个数字
for (int j = 0; j < i; j++) {
if (arrayofInts[j] > arrayofInts[j + 1]) {
int temp = arrayofInts[j];
arrayofInts[j] = arrayofInts[j + 1];
arrayofInts[j + 1] = temp;
}
}
}

// 循环整个数组
for (int i = 0; i < arrayofInts.length; i++) {
System.out.println("arrayofInts[" + i + "]=" + arrayofInts[i] + " at " + position.get(arrayofInts[i]));
}
}
------解决方案--------------------
借用你的代码。因为有重复数据 所以有的判断不是很一致吧
Java code
public class SortDemo { 
  public SortDemo() { 
  } 
  public static void main(String[] args) { 
    SortDemo sortDemo1 = new SortDemo(); 
    //初始化变量 
    int[] arrayofInts = {12,8,3,59,132,1236,3400,8,352,37}; 
    int[] backUpArray = {12,8,3,59,132,1236,3400,8,352,37};

    //循环整个数组 
    for(int i=arrayofInts.length; --i>=0;){ 
      //循环每个数字 
      for(int j=0;j <i;j++){ 
        if(arrayofInts[j]>arrayofInts[j+1]){ 
          int temp=arrayofInts[j]; 
          arrayofInts[j]=arrayofInts[j+1]; 
          arrayofInts[j+1]=temp; 
        } 
      } 
    } 
    //循环整个数组 
    for(int i=0;i <arrayofInts.length;i++){ 
      System.out.print("arrayofInts["+i+"]="+arrayofInts[i]); 
      
      for (int j=0; j<backUpArray.length; j++){
          if (arrayofInts[i] == backUpArray[j]){
              System.out.print("In former array, the index is: "+ j +"\n");
          }
      }
    } 
  } 
}