2015-05-13 165 views
-5

我想要按名称对此数据进行排序,我使用以下代码,任何人都可以告诉我它有什么问题吗?它没有完美地对数据进行排序。按名称排序数组

条件是我们必须使用两个while循环而仅循环。

   Sales and Commission 
    ====================================================== 
    Salesperson  Sales Amount  Commission 
    ----------------------------------------------------- 
    h h     $54000   $4320.0 
    jghu jghf   $90000   $9000.0 
    hg gf    $45000   $2700.0 
    kaushal garg  $87000   $8700.0 
    kfhfuyd dhd   $32000   $1920.0 

    Total: 9 Data entries 

代码:

public static void sortByName() { 
    int small;  // Two while loop and one if loop for sorting 
    int i = 0;  // the data based on sales amount 
    while (i < name.length) { 
     small = i; 
     int index = i + 1; 
     while (index < name.length) { 

      if (name[index].compareToIgnoreCase(name[small]) < 0) { // name comparision for sorting 
       small = index; 
      } 
      swap(i, small); // caling the swap method 
      index++; 

     } 
     i++; 
    } 
    displayData();    // calling displayData function. 
} 

//Method used in the sorting the data based on name and sales 
public static void swap(int first, int second) { 
    String temp = name[first]; 
    name[first] = name[second]; 
    name[second] = temp; 


} 
+0

看到这个:http://stackoverflow.com/questions/12986386/sorting-an-array-of-strings-with-java – pcj

+0

你的名字是阵列是一个String []? –

+0

是否有必要使用数组?你也可以使用一个ArrayList并编写一个自定义的Comparator – Dragondraikk

回答

0

我认为这个问题是在内部循环的交换功能,因为它会始终执行。也许它应该发生在if范围内(根据compareToIgnoreCase()函数的返回,不太确定)。

while (index < name.length) { 

      if (name[index].compareToIgnoreCase(name[small]) < 0) { // name comparision for sorting 
       small = index; 
       swap(i, small); // caling the swap method 
      } 

      index++; 

     } 
0

看来你试图实现一个冒泡排序。首先,没有像“if-loop”这样的事情,这是一个if条件。我发现你的变量名称很混乱,所以我重命名了它们中的大部分。下面的代码应该可以工作。

public static void sortByName() { 
    int i = 1; 
    while (i < name.length) { 
     int j = 0; 
     while (j < name.length - i) { 
      if (name[j].compareToIgnoreCase(name[j + 1]) > 0) { 
       //you should be able to figure out yourself, what to do here   
      } 
      j++; 
     } 
     i++; 
    } 
    displayData(); 
} 
+0

m抱歉输入错误.. m试图学习..感谢您的帮助 –

+0

您可以给你的变量任何你想要的名字。我只是无法理解你的代码;-) – Steffen