1#include <stdio.h> 2 3void exchange(int* array, int p1, int p2) 4{ 5 if (p1 == p2) 6 return; 7 int temp = array[p1]; 8 array[p1] = array[p2]; 9 array[p2] = temp; 10} 11 12void insertSort(int* array, int len) 13{ 14 int sorted = 0; //the 1st data we think was already sorted 15 int cur; 16 for (cur = 1; cur < len; cur++)//start from 2nd data 17 { 18 //loop with sorted range 19 int sort; 20 for (sort = 0; sort <= sorted; sort++) 21 { 22 if (array[cur] <= array[sort]) 23 { 24 // let current data move forward one by one and stop at right postion 25 int curPos = cur; 26 while (curPos != sort) 27 { 28 exchange(array, curPos, curPos - 1); 29 curPos--; 30 } 31 break; 32 } 33 } 34 sorted++; 35 } 36} 37 38//From Intruduction Of Alogrithim 39void insertSort1(int* array, int len) 40{ 41 for (int i = 1; i < len; i++)//loop start from 2nd data cause we think 1st is already sorted 42 { 43 int key = array[i];//current data we call it key 44 int j = i - 1;//watch pre data of key 45 while (j >= 0 && array[j] > key) 46 { 47 array[j+1] = array[j];//if pre data bigger, move to right 48 j--;//if pre data stiill bigger than key, move to right 49 }//end while for moving 50 array[j + 1] = key;// when move over the postion `j+1` was empty insert the key 51 } 52} 53 54void main() 55{ 56 intarray[10] = { 1, 8, 3, 6, 2, 4, 7, 5, 9, 0 }; 57 printf("before:"); 58 int i; 59 for (i = 0; i <= sizeof(array) - 1; i++) 60 { 61 printf("%d ", array[i]); 62 } 63 printf("\n"); 64 insertSort(array, sizeof(array)); 65 printf("\n after:"); 66 for (i = 0; i <= sizeof(array) - 1; i++) 67 { 68 printf("%d ", array[i]); 69 } 70 return; 71}
C语言 插入排序 Insert Sort
Stella981
2021-10-11
1096 0 0
点赞
收藏
评论区
加载中...