Java Bubble sorting not working -
i want write program sorts 3 integers. integers entered input dialog. code simple. need data , put them in array called num
. , create method sort data using bubble-sort logic. method called sort
. have added command display sorted result system.out.println("sorted result : "+arrays.tostring(num))
that's not working. output let me input data , nothing happen.
can please tell me miss or did wrong? thank you.
package numthree; import java.util.scanner; import java.util.arrays; public class sort { public static void main(string[] args) { scanner sc = new scanner(system.in); int[] num = new int[3]; //input data system.out.println("enter integers : "); for(int i=0;i<=num.length;i++){ num[i]=sc.nextint(); } sort(num); } //sorting public static void sort (int[] num){ for(int i=0;i<=num.length-1;i++){ for(int j=0;j<=num.length-i;j++){ if(num[j-1]>num[j]){ int temp = num[j]; num[j] = num[j-1]; num[j-1] = temp; } } system.out.println("sorted result : "+arrays.tostring(num)); } } }
i believe need boolean flag implement bubble sort cannot know in advance how many times loop perform swapping of consecutive elements.
try this:
package numthree; import java.util.scanner; import java.util.arrays; public class sort { public static void main(string[] args) { scanner sc = new scanner(system.in); int[] num = new int[3]; //input data system.out.println("enter integers : "); for(int i=0;i<=num.length;i++){ num[i]=sc.nextint(); } sort(num); } //sorting public static void sort (int[] num){ boolean swapped = true; while(swapped){ swapped = false; for(int i=0;i<num.length-1;i++){ if(num[i]>num[i+1]){ int temp = num[i]; num[i] = num[i+1]; num[i+1] = temp; swapped = true; } } } system.out.println("sorted result : "+arrays.tostring(num)); } }
note can still improved: each time around loop largest number end far can towards end of of array: there's no need check or swap till end each time. using variable upper limit of index i
, decreasing value after loop can reduce total number of iterations.
int end = num.length-1; while(swapped){ swapped = false; for(int i=0;i<end;i++){ if(num[i]>num[i+1]){ int temp = num[i]; num[i] = num[i+1]; num[i+1] = temp; swapped = true; } } end--; }
Comments
Post a Comment