-5

I want this data to be sort by name, I'm using the following code, can anyone please tell me what's wrong with it? It's not sorting the data perfectly.

The condition is we have to use two while and if loop only.

             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

Code:

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;


}
halfer
  • 19,824
  • 17
  • 99
  • 186

2 Answers2

0

I think the problem is the swap function in the inner loop, because it will be executed always. Maybe it should occurred in the if scope(not very sure, according to the return of function of 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++;

        }
Xin Meng
  • 1,982
  • 3
  • 20
  • 32
0

It seems you are trying to implement a bubble sort. First of all, there is no such thing as an "if-loop" it's an if-condition. I found your variable names quite confusing so I renamed most of them. The following code should work.

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();
}
Steffen
  • 46
  • 5