算法001.插入排序

 1 #include <iostream>;
 2 
 3 using namespace std;
 4 void insertion_sort(int * arr, int length);
 5 
 6 int main()
 7 {
 8     int arr[] = {2,45,5,8,10,4,9,45,8,36,159,125,134,147,155};
 9     int length = sizeof(arr)/sizeof(int);
10     insertion_sort(arr, length);
11     for (int i = 0; i< length; i++)
12     {
13         cout << arr[i] << endl;
14     }
15     cin.get();
16 
17 }
18 
19 void insertion_sort(int * arr, int length)
20 {
21     int i, j;
22     for(i = 1; i < length; i++)
23     {
24         int temp = arr[i];
25         j = i - 1;
26         while (j >= 0 && arr[j] > temp)
27         {
28             arr[j+1] = arr[j];
29             j--;
30         }
31         arr[j+1] = temp;
32         
33     }
34 }

记录下学习算法的过程,原理相信看算法导论会更清楚,文字表达能力太差,也就不说了,附上js的,和c++一样,当作自己的复习

 1 var arr = [2, 45, 5, 8, 10, 4, 9, 45, 8, 36, 159, 125, 134, 147, 155];
 2 arr = insertionSort(arr);
 3 console.log(arr);
 4 function insertionSort(arr) {
 5     var i, j, temp;
 6     for (i = 1; i < arr.length; i++) {
 7         temp = arr[i];
 8         j = i - 1;
 9         while (j >= 0 && arr[j] > temp) {
10             arr[j + 1] = arr[j];
11             j--;
12         }
13         arr[j+1] = temp
14     }
15     return arr;
16 }

 

posted on 2014-10-12 01:36  a2htray  阅读(513)  评论(0编辑  收藏  举报

导航