java - Can somebody explain the last method in this code? -


i'm beginner programmer , don't understand last method (mysort) in code. it's example bubble sort.

import java.util.*; public class sort { public static void main(string[] args) {     int[] = {22, 55, 44, 11, 33};     disp(a);     mysort(a);     disp(a); } public static void disp(int[] x) {     for(int e : x)     {         system.out.print(e + "\t");     }     system.out.println(); }  public static void mysort(int[] a) {     int l = a.length;     for(int = 0; < l - 1; i++)     {         for(int j = 0; j < l - 1 - i; j++)         {             if(a[j + 1] < a[j])             {                 int temp = a[j];                 a[j] = a[j + 1];                 a[j + 1] = temp;             }         }     } } } 

let's break down each piece of method. first part of code understand inner block:

int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; 

if run above statements on array {1,2,3,4,5}, j=2, have:

int temp = a[2] --> 3; a[2] = a[2+1] --> = {1,2,4,4,5}; a[2+1] = temp --> = {1,2,4,3,5}; 

we see these 3 lines swap elements of a[j] , a[j+1].

now @ loops. inner loop: for(int j = 0; j < l - 1 - i; j++) looping start of array l-1-i. @ each index, asks if(a[j+1] < a[j]), meaning "is element @ index j+1 smaller element @ index j", or more concretely, "should elements @ j+1 , j swapped?"

the outer loop running on whole array index variable i. taking 2 loops together, see j first loop on whole array without last index, whole array without last 2 indices, without last three, etc. example, if l = 10, j take on values:

0 1 2 3 4 5 6 7 8 //i = 0, l - 1 - = 9 0 1 2 3 4 5 6 7   //i = 1, l - 1 - = 8 0 1 2 3 4 5 6     //i = 2, l - 1 - = 7 ... 0 

so 2 loops running on fraction of array l times, making swaps.

the reason loops being formed way after each iteration of j=0...l-1-i, last element known in sorted location, don't have check again. justification , more here: http://en.wikipedia.org/wiki/bubble_sort


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -