public class Sort {
/**
* æ’入排åºçš„åŸºæœ¬æ€æƒ³ä¸ºï¼šé¦–å…ˆå¯ÀL‰¾ä¸€ä¸ªæœ‰åºæ•°åˆ—,然厞®†æ•°¾l„ä¸çš„æ¯ä¸ªå…ƒç´ æ’入到该有åºåºåˆ—ä¸åQ?br />
* 则该数组åºåˆ—å›_¯å˜äØ“æœ‰åºæ•°åˆ—ã€‚å…·ä½“å®žæ–½åŠžæ³•äØ“åQŒé¦–选将½W¬ä¸€ä¸ªå…ƒç´ 看作是一个有åºåºåˆ—,然åŽ
* ä»Žç¬¬äºŒä¸ªå…ƒç´ å¼€å§‹é历数¾l„,ž®†æ¯ä¸ªå…ƒç´ æ’å…¥åˆ°ä»Žç¬¬ä¸€ä¸ªå…ƒç´ åˆ°å‰ä¸€ä¸ªå…ƒç´ 的有åºåºåˆ—ä¸ï¼Œå›_¯å®?br />
* æˆæŽ’åºã€?br />
* @param temp
*/
/*
public static void insertSort(int[] temp)
{
int length = temp.length;
for (int i = 1; i < length; i++) // æŠŠç¬¬ä¸€ä¸ªå…ƒç´ çœ‹ä½œä¸€ä¸ªæœ‰åºåºåˆ—ï¼Œä»Žç¬¬äºŒä¸ªå…ƒç´ å¼€å§‹éåŽ?br />
{
int tempNo = temp[i];
for (int j = 0; j < i; j++)
{
if (tempNo < temp[j])
{
for (int k = i; k > j; k--) // ž®†å…¶é历数和比较æ•îC¹‹é—´çš„æ•îC¾‹Æ¡å‘åŽç§»åЍ䏀ä½?br />
temp[k] = temp[k-1];
temp[j] = tempNo;
}
}
}
}
*/
/**
* javaeye上看到的å¦å¤–一¿U写法,ä¸åŒä¹‹å¤„是其与å‰è¾ÒŽ(gu¨©)•°å—一个一个比较,然åŽä¸€‹Æ¡ä¸€‹Æ¡é€æ¸¿UÕdЍã€?br />
*/
/*
public static void insertSort(int[] a)
{
for(int i = 1; i < a.length; i++)
{
int temp = a[i];
int j = i - 1;
while (j >= 0 && temp < a[j])
{
a[j+1] = a[j];
j--;
}
a[j+1] = temp;
}
}
*/
/**
* 数殾l“构书上原版½Ž—法的java代ç 实现
*/
public static void insertSort(int[] temp)
{
int j = 0;
int length = temp.length;
int[] a = new int[length+1];
System.arraycopy(temp, 0, a, 1, length);
for(int i = 2; i < a.length; i++)
{
if(a[i] < a[i-1])
{
a[0] = a[i];
a[i] = a[i-1];
for (j = i - 2; a[i] < a[i-1]; j--)
{
a[j+1] = a[j];
}
a[j+1] = a[0];
}
}
for (int i = 1; i < a.length; i++)
{
System.out.println(a[i]);
}
}
/**
* æŠ˜åŠæ’å…¥æŽ’åº½Ž—æ³•çš„java实现
* @param temp
*/
public static void bInsertSort(int[] temp)
{
int length = temp.length;
for (int i = 1; i < length; i++)
{
int tempVal = temp[i];
int low = 0;
int high = i - 1;
while (low <= high)
{
int middle = (low + high) / 2;
if (tempVal < temp[middle])
high = middle - 1;
else
low = middle + 1;
}
for (int j = i; j > high + 1; j--)
temp[j] = temp[j-1];
temp[high+1] = tempVal;
}
}
public static void buddleSort(int[] temp)
{
for (int i = 0; i < temp.length - 1; i++)
{
for (int j = i + 1; j < temp.length; j++)
{
if (temp[i] > temp[j])
{
int tempVal = temp[i];
temp[i] = temp[j];
temp[j] = tempVal;
}
}
}
}
public static void main(String[] args)
{
int a[] = {113, 3, 24, 24, 78, 96};
Sort.bInsertSort(a);
//Sort.insertSort(a);
//Sort.buddleSort(a);
for (int i = 0; i < a.length; i++)
{
System.out.println(a[i]);
}
}
}