I am trying to write a class in java that will populate an array with random numbers, print the array, and then sort the array using the algorithm:
ap = size / 2
do until gap <= 0
swapflag = true
do until swapflag is false
swapflag = false
for s = 0 to size – gap
if num[s] > num[s + gap]
swap num[s] with num[s + gap]
swapflag = true
end‐if
end‐for
end‐do
gap = gap / 2
end‐do
Below is my code so far, and I think I am having trouble using the comparable T interface with the data type for the array. Any help or suggestions would be much appreciated, thanks!
``` import java.util.*;
public class Sort {
public static void main( String ... args ) {
Random random = new Random();
Integer[][] array = new Integer[1][10];
for( int i = 0 ; i < array.length ; i++ ) {
for ( int j = 0 ; j < array[i].length ; j++ ) {
array[i][j] = random.nextInt(100);
}
}
for( Integer[] a : array ) {
System.out.println( "Array before sorting:");
System.out.println( Arrays.toString( a ));
System.out.println( "Array after sorting:");
shellSort(array);
for (int num: array)
System.out.println(num);
}
}
public static <T extends Comparable<T>> void shellSort(T[] data)
{
int gap, i, j;
for (gap = data.length / 2; gap > 0; gap /= 2)
{
for (i = gap; i < data.length; i++)
{
T temp = data[i]; //store the original data to a temp position
for (j = i; j >= gap &&temp.compareTo(data[ j - gap ]) < 0; j -= gap ) // Compare the data on position on j and position j-gap.
{
data[j] = data[j-gap]; //If number on j position is smaller than the number on (j-gap) position, swap them.
}
//---------------------------------------------------------------------------------------------------------
//If the loop of j is excuted, postion j now is actually postion j-gap from the loop of j.
//Set position j -gap in the loop of j, which is j below, equal to the value of temp.
//If the loop of j is not excuted, position j below equals to the value of temp, no swap.
//---------------------------------------------------------------------------------------------------------
data[j] = temp;
}
}
}
}
```
Aucun commentaire:
Enregistrer un commentaire