I'm still very new to Java and this is an assignment for school where I'm to create a ShellSort class and driver class. The ShellSort class should create and populate an array of n size, and contains a shell sort method using the following pseudo-code:
This is the code I have so far:
import java.util.*;
public class ShellArray {
int array[] = null;
int size=0;
Random random = new Random();
int gap = 0;
public ShellArray (int size) {
this.size = size;
array=new int[size];
for (int i = 0; i<size; i++) {
this.array[i]=random.nextInt(100);
}
System.out.println("Your array is: ");
for(int i=0; i<size;i++) {
System.out.print(" " +array[i] + " ");
}
}
public int[] shellSort(int size) {
gap = size/2;
do {
boolean swapflag = true;
do {
swapflag = false;
for (int s = 0; s<(size-gap);s++) {
if (array[s] > array[s+gap]) {
//swap array[s] with array[s+gap]
swapflag = true;
}
}
}
while (swapflag != false);
}while (gap>0);
gap = gap/2;
}
public String toString () {
//to output array results of each swap
}
}
I'm lost as to how to swap array[s] with array[s+gap] and how to use toString to output array at each swap.
I've tried using a "temp" variable to put array[s] in, so I can put array[s+gap] into array[s]'s index, but I received "ShellArray@7c53a9eb" error?
Any help will be much appreciated! Thank you.
System.out.println(Arrays.toString(array))
To swap array element,
if (array[s] > array[s + gap]) {
int temp = array[s];
array[s] = array[s + gap];
array[s + gap] = temp;
// swap array[s] with array[s+gap]
swapflag = true;
}
In addition, it seems gap = gap/2;
is should be inside the first do while loop.