c# - My BubbleSort class does not count iterations correctly -


this my program

static void main(string[] args)         {              int[] arraytosort = new int[] { 5,4,9};             bubblesort bubblesort = new bubblesort();             int [] sortedarray = bubblesort.sortarray(arraytosort);             foreach (int in sortedarray)                 console.write(i.tostring() + "," );             console.writeline("number of iterations {0}",                                   bubblesort.iterationscounter);             console.readline();              }   public class bubblesort     {         public int iterationscounter;         public int[] sortarray(int[] arraytosort)         {             for(int = 0;i<arraytosort.length-1;i++)             {                 if(arraytosort[i]>arraytosort[i+1])                 {                     int temp=arraytosort[i];                     arraytosort[i]=arraytosort[i+1];                     arraytosort[i+1]=temp;                     //iterationscounter++;  update:moved line out of if condition)                     sortarray(arraytosort);                 }             iterationscounter++; //moved counter here:              }             return arraytosort;     } 

output:

4,5,9 number of iterations:1 

how can right? mean array sorted surely there more 1 iteration. expecting have o(n^2) running time off here. not counting iterations right?

edit:

ok realized 3 items isn't enough , per suggestion moved counter out of if , , if change input to

 5,4,9,2,3,1,17 

number of iterations changes 78 . thats better( in sense should high) not high enough. means algorithm has o(logn) time? thought bubblesort o(n^2)?

thank you

you counting number of swap operation, not iterations. average running time of bubble sort o(n^2), , doesn't mean every bubble sort must many iterations. example, if bubble sort sorted array, , set flag if swap made after entire pass on array. if no swap made, should clear array in order because no 2 elements need swapped. in case, bubble sort should end. seems faster quicksort average time complexity o(n log n) since performance of modified bubble sort o(n) in scenario. must take account of general cases.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -