首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

数组排序的有关问题

2011-12-30 
数组排序的问题下面程序实现冒泡排序,最后输出3 8 8 12 37 59 132 352 1236 3400我想最后不仅输出排序好的

数组排序的问题
下面程序实现冒泡排序,最后输出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");          }      }    }   } } 

热点排行