Topic: 我写的冒泡排序错在哪?

  Print this page

1.我写的冒泡排序错在哪? Copy to clipboard
Posted by: chenxi09751200
Posted on: 2009-04-23 15:49

我是新手 不知道哪错了 哪位大虾帮忙看下

    int[] i = { 2, 5, 8, 4, 7 };
    int l = i.length;
    int j;
    for (int m = 0; m < l; m++) {
      for (int n = 1; n < l - m - 1; n++) {
        if (i[m] > i[m + 1]) {
          j = i[m];
          i[m] = i[m + 1];
          i[m + 1] = j;
        }
      }
      System.out.print(i[m] + " ");
    }
结果:2 5 4 8 7

2.Re:我写的冒泡排序错在哪? [Re: chenxi09751200] Copy to clipboard
Posted by: jackieban
Posted on: 2009-04-24 15:53

你进行的比较不对应该这样

import java.lang.*;

public class ebullition{
  public static void main(String args[]){
     int[] i = { 2, 5, 8, 4, 7 };
   int l = i.length;
   int j;
   for (int m = 0; m < l; m++) {
   for (int n = 1; n < l - m - 1; n++) {
   if (i[n] > i[n + 1]) {
   j = i[n];
   i[n] = i[n + 1];
   i[n + 1] = j;
   }
   }
   //System.out.print(i[m] + " ");
   }  
  
   for(int m = 0; m<l; m++){
     System.out.print(i[m] + " ");
   }

  }
}


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923