Linux教程網
C語言算法--插入排序
- /*-----------------------------
- *
- * For 排序算法學習
- * IDE DEV-CPP4.9.2
- * Auhtor Czp
- * Date 2012/10/17
- *------------------------------
- */
- #include <stdlib.h>
- #include <stdio.h>
- //插入排序
- void insertSort(int* arr,size_t n)
- {
-
- int i,j,key;
- for(i=1;i<n;i++) //初始:ar={169,45,2,489,469,4,-778,156}
- {
- key = arr[i];
- j=i-1;
- while(j>=0&&arr[j]>key) //把key與前面的arr[0~j]進行比較
- arr[j+1] = arr[j--]; //找到一個比key大的數就把它後移
- arr[j+1]=key; //上面的循環終止,則j+1就key的位置
- }
- /*
- *Loop0:169,45,2,489,469,4,-778,156 數組原型 取key=arr[2]=2
- *Loop1:2,169,45,489,469,4,-778,156 key=2比arr[1] arr[0]小,找到arr[2]的位置arr[0]->
- *Lopp3:2,169,45,469,489,4,-778,156 進行插入和ArrayList的insert(value,index)一樣
- *Loop4:2,169,45,469,489,4,-778,156 .......
- *Loop5:2,4,169,45,469,489,-778,156 ...
- *Loop6:-778,2,4,169,45,469,489,156 ...
- *Loop7:-778,2,4,156,169,45,469,489 ...
- */
- }
-
- int main(int argc, char *argv[])
- {
- int arr[] = {169,45,2,489,469,4,-778,156};
- size_t len = (sizeof arr/sizeof arr[0]);
- insertSort(arr,len);
- int i;
- for(i=0;i<len;i++)
- {
- printf("%d ,",arr[i]);
- }
- //====>-778,2,4,156,169,45,469,489
- getchar();
- return 0;
- }
Copyright ©
Linux教程網 All Rights Reserved