北京北大青鳥通州校區(qū)學(xué)術(shù)部老師講解:什么是希爾排序?
北京北大青鳥專家解答:希爾排序就是對插入排序的優(yōu)化, 他是把一個(gè)待排序的數(shù)組分段成有規(guī)律的的若干個(gè)數(shù)組排序,最后在進(jìn)行總排序來完成排序的目的,
基本思想:先取一個(gè)小于n的整數(shù)d1作為第一個(gè)增量,把文件的全部記錄分成d1個(gè)組。所有距離為d1的倍數(shù)的記錄放在同一個(gè)組中。先在各組內(nèi)進(jìn)行直接插入排序;然后,取第二個(gè)增量d2
(1)將等間距的數(shù)組元素按升序排列(北京北大青鳥校區(qū))
view plaincopy to clipboardprint?
private static void incrementalInsertionSort(int[] array, int first,
int last, int space)
{
int unsorted, index;
for (unsorted = first + space; unsorted <= last; unsorted += space)
{
int firstUnsorted = array[unsorted];
for (index = unsorted - space; (index >= first)
&& (firstUnsorted < array[index]); index -= space)
{
array[index+space] = array[index];
}
array[index+space] = firstUnsorted;
}
}
private static void incrementalInsertionSort(int[] array, int first,
int last, int space)
{
int unsorted, index;
for (unsorted = first + space; unsorted <= last; unsorted += space)
{
int firstUnsorted = array[unsorted];
for (index = unsorted - space; (index >= first)
&& (firstUnsorted < array[index]); index -= space)
{
array[index+space] = array[index];
}
array[index+space] = firstUnsorted;
}
}
2)設(shè)定索引間距序列(北京北大青鳥校區(qū))
view plaincopy to clipboardprint?
public static void shellSort(int[] array, int first, int last)
{
int n = last-first + 1;
for (int space = n / 2; space > 0; space /= 2)
{
for (int begin = first; begin < first + space; begin++)
{
incrementalInsertionSort(array, begin, last, space);
}
}
}
public static void shellSort(int[] array, int first, int last)
{
int n = last-first + 1;
for (int space = n / 2; space > 0; space /= 2)
{
for (int begin = first; begin < first + space; begin++)
{
incrementalInsertionSort(array, begin, last, space);
}
}
}
3)測試(北京北大青鳥校區(qū))
view plaincopy to clipboardprint?
public static void main(String[] args)
{
// TODO Auto-generated method stub
Random random = new Random();
final int size = 10;
int i;
int[] array = new int[size];
for (i = 0; i < size; i++)
{
array[i] = random.nextInt(1000);
}
System.out.println("排序前數(shù)組");
for (i = 0; i < size; i++)
{
if((i+1) % 20 == 0)
{
System.out.println();
}
else
{
System.out.print(array[i] + " ");
}
}
shellSort(array,0,size-1);
System.out.println("\n排序后數(shù)組");
for (i = 0; i < size; i++)
{
if((i+1) % 20 == 0)
{
System.out.println();
}
else
{
System.out.print(array[i] + " ");
}
}
}
(北京北大青鳥校區(qū))