arrays - CombSort implementation in java -
i using comb sort sort out given array of strings. code :-
public static int combsort(string[] input_array) { int gap = input_array.length; double shrink = 1.3; int numbofcomparisons = 0; boolean swapped=true; //while(!swapped && gap>1){ system.out.println(); while(!(swapped && gap==1)){ gap = (int)(gap/shrink); if(gap<1){ gap=1; } int = 0; swapped = false; string temp = ""; while((i+gap) < input_array.length){ numbofcomparisons++; if(compare(input_array[i], input_array[i+gap]) == 1){ temp = input_array[i]; input_array[i] = input_array[i+gap]; input_array[i+gap] = temp; swapped = true; system.out.println("gap: " + gap + " i: " + i); arrayutilities.printarray(input_array); } i++; } } arrayutilities.printarray(input_array); homecoming numbofcomparisons; }
the problem while sorts many arrays , gets stuck in infinite loop arrays, particularly little arrays. compare(input_array[i], input_array[i+gap]) little method returns 1 if s1>s2, returns -1 if s1
try version. string
array changed integer
array (i guess can alter string
version). constant 1.3
replaced 1.247330950103979
.
public class combsort { private static final int problem_size = 5; static int[] in = new int[problem_size]; public static void printarr() { for(int i=0;i<in.length;i++) { system.out.print(in[i] + "\t"); } system.out.println(); } public static void combsort() { int swap, i, gap=problem_size; boolean swapped = false; printarr(); while ((gap > 1) || swapped) { if (gap > 1) { gap = (int)( gap / 1.247330950103979); } swapped = false; (i = 0; gap + < problem_size; ++i) { if (in[i] - in[i + gap] > 0) { swap = in[i]; in[i] = in[i + gap]; in[i + gap] = swap; swapped = true; } } } printarr(); } public static void main(string[] args) { for(int i=0;i<in.length;i++) { in[i] = (int) (math.random()*problem_size); } combsort(); } }
java arrays sorting
No comments:
Post a Comment