sorting - Basic Bubble Sort with ArrayList in Java -


i implementing comparator, , wasn't working, thought i'd write basic bubble sort.

int[] numbers = { 5, 8, 14, 1, 5678 }; int tempvar; (int = 0; < numbers.length; i++) {    for(int j = 0; j < numbers.length; j++)    {             if(numbers[i] > numbers[j + 1])             {                    tempvar = numbers [j + 1];                    numbers [j + 1]= numbers [i];                    numbers [i] = tempvar;             }    } } (int = 0; < numbers.length; i++) {      system.out.println(numbers[i].tostring()); } 

is tutorial correct @ all? https://blog.udemy.com/bubble-sort-java/

i followed example , applied last names in arraylist, results bit wack.

string a; string b; person c; person d;  (int i=0; i< list.size(); i++){      for(int j=0; j< list.size()-1; j++){           = list.get(i).getlastname();          b = list.get(j+1).getlastname();          c = list.get(i);          d = list.get(j+1);           if ( a.compareto(b) < 0 )  {               person temp = d;              list.set(j+1, c);                      list.set(i, temp);           }      }  } 

i'd grip on few methods (like figuring out why comparator didn't work), right i'd bubble sort work correctly. thanks.

in bubble sort need compare adjacent elements , swap them(depending on condition).

if doing ascending order comparing adjacent elements , swap if(arr[j]>arr[j+1]). moves largest elements end in first iteration.thus there n-1 iterations in outer loop sort array n length of array.

read first bubble sort tutorial mentioned wrong

corrected code

for (int = 0; < numbers.length-1; i++) {    for(int j = 0; j < numbers.length-i-1; j++)    {             if(numbers[j] > numbers[j + 1])             {                    tempvar = numbers [j + 1];                    numbers [j + 1]= numbers [j];                    numbers [j] = tempvar;             }    } } 

here working link


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -

jdbc - Not able to establish database connection in eclipse -