When my sort is run on this data {7,8,4,2,3,9,5,8,4,1} only the first element is not put in its correct place. How can I fix this? Thanks for the help.
public void segmentedInsertionSort(int[] array, int size, int h)
{
int temp;
for(int i = h + 1 ;i < size;i++)
{
int j = i - h;
while(j > 0)
{
if(array[j+h] < array[j])
{
temp = array[j];
array[j] = array[j+h];
array[j+h] = temp;
j = j - h;
}
else
{
j = 0;
}
}
}
}
public void shellSort(int[] array, int size)
{
int h = size/2;
while(h > 0)
{
segmentedInsertionSort(array,size,h);
h = h/2;
}
}
I think you have misvalued some variables.Your variable
j
never reaches index 0 so as to compare 7 with any other value in this Comparison Sort.Change:
for(int i = h +1 ;i < size;i++)
tofor(int i = h ;i < size;i++)
And
while(j > 0)
towhile(j >= 0)
else { j = 0; }
to
else{ j = -1; }
Final Code looks like: