How to populate a random array, then sort it in Java? -
i trying write class in java populate array random numbers, print array, , sort array using algorithm:
ap = size / 2 until gap <= 0 swapflag = true until swapflag false swapflag = false s = 0 size – gap if num[s] > num[s + gap] swap num[s] num[s + gap] swapflag = true end‐if end‐for end‐do gap = gap / 2 end‐do
below code far, , think having trouble using comparable t interface data type array. or suggestions appreciated, thanks!
edit* there 2 error messages code below:
1) method shellsort(t[]) in type sort not applicable arguments (integer[][]) sort.java
2) type mismatch: cannot convert element type integer[] int sort.java
***lines error surrounded stars
import java.util.*; public class sort { public static void main( string ... args ) { random random = new random(); integer[][] array = new integer[1][10]; for( int = 0 ; < array.length ; i++ ) { ( int j = 0 ; j < array[i].length ; j++ ) { array[i][j] = random.nextint(100); } } for( integer[] : array ) { system.out.println( "array before sorting:"); system.out.println( arrays.tostring( )); system.out.println( "array after sorting:"); ***shellsort(array); (int num: array)*** system.out.println(num); } } public static <t extends comparable<t>> void shellsort(t[] data) { int gap, i, j; (gap = data.length / 2; gap > 0; gap /= 2) { (i = gap; < data.length; i++) { t temp = data[i]; //store original data temp position (j = i; j >= gap &&temp.compareto(data[ j - gap ]) < 0; j -= gap ) // compare data on position on j , position j-gap. { data[j] = data[j-gap]; //if number on j position smaller number on (j-gap) position, swap them. } //--------------------------------------------------------------------------------------------------------- //if loop of j excuted, postion j postion j-gap loop of j. //set position j -gap in loop of j, j below, equal value of temp. //if loop of j not excuted, position j below equals value of temp, no swap. //--------------------------------------------------------------------------------------------------------- data[j] = temp; } } } }
Comments
Post a Comment