当前位置:   article > 正文

数据结构与算法分析(排序,递归,链表)

数据结构与算法分析

1.C提供形如

#include <filename> 的语句,它读入文件filename并将其插到include语句处,include语句可以嵌套,换句话说,文件filename本身还可以包含include语句,但是显然一个文件在任何链接中不能包含它自己,编写一个程序,使它读入被include语句修饰的一个文件,并输出这个文件。

为什么递归调用要求不能包含它自己?因为那样会破坏递归要求有终点的约定,递归是重复调用,但不是无限调用,递归一定是有结束的,从形式上说,递归类似于无环的树结构,而如果文件链接包含的不是其它文件,而是自己,则会引入依赖环。

  1. #include<iostream>
  2. #include<string>
  3. #include<vector>
  4. #include<fstream>
  5. #include<algorithm>
  6. using namespace std;
  7. vector<string> files;
  8. void ProcessFile(const string& filename)
  9. {
  10. string line;
  11. ifstream in(filename);
  12. if (in.fail()) {
  13. cerr << "fail to open file " << filename << endl;
  14. return;
  15. }
  16. files.push_back(filename);
  17. while (getline(in, line)) {
  18. if (line.find("#include") != string::npos) {
  19. string::size_type beg = line.find_first_of("<\"");
  20. string::size_type end = line.find_last_of(">\"");
  21. string file = line.substr(beg + 1, end - beg - 1);
  22. if (find(files.begin(), files.end(), file) != files.end()) {
  23. cerr << "Existed file " << file << endl;
  24. continue;
  25. } else {
  26. ProcessFile(file);
  27. }
  28. } else {
  29. cout << line << endl;
  30. }
  31. }
  32. in.close();
  33. }
  34. int main()
  35. {
  36. ProcessFile("test.h");
  37. return 0;
  38. }

编译:

头文件内容

运行结果:


2.算法时间复杂度分析中几种典型的增长率函数。

3.快速排序的经典实现:

快速排序是一种基于分治思想的排序算法,该算法的主要步骤是选择一个基准值(pivot),将待排序序列划分为左右两个子序列,并对左右子序列递归进行排序,直到整个序列有序。

在快速排序过程中指针移动的方式通常是从数组连贯开始逐步移动并互相交换元素,而不是使用中间指针,这种交替移动指针的方式可以保证快速排序同时满足以下两个特性:

1.分治:算法每次选择一个基准值将序列划分为左右两个子序列,这样可以使得左子序列的所有元素都小于等于基准值,右子序列的所有元素都大于等于基准值,随后,继续对左右子序序列递归进行排序。

2.原地排序:该算法不需要借助额外的数据结构来实现排序,只需要在原数组中交换元素即可,这种方式可以节省空间并减少程序的运行时间。

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. //快速排序算法(从小到大)
  5. //arr:需要排序的数组,begin:需要排序的区间左边界,end:需要排序的区间的右边界
  6. void quickSort(int *arr,int begin,int end)
  7. {
  8. //如果区间不只一个数
  9. if(begin < end)
  10. {
  11. int temp = arr[begin]; //将区间的第一个数作为基准数
  12. int i = begin; //从左到右进行查找时的“指针”,指示当前左位置
  13. int j = end; //从右到左进行查找时的“指针”,指示当前右位置
  14. //不重复遍历
  15. while(i < j)
  16. {
  17. //当右边的数大于基准数时,略过,继续向左查找
  18. //不满足条件时跳出循环,此时的j对应的元素是小于基准元素的
  19. while(i<j && arr[j] > temp)
  20. j--;
  21. //将右边小于等于基准元素的数填入右边相应位置
  22. arr[i] = arr[j];
  23. //当左边的数小于等于基准数时,略过,继续向右查找
  24. //(重复的基准元素集合到左区间)
  25. //不满足条件时跳出循环,此时的i对应的元素是大于等于基准元素的
  26. while(i<j && arr[i] <= temp)
  27. i++;
  28. //将左边大于基准元素的数填入左边相应位置
  29. arr[j] = arr[i];
  30. }
  31. //将基准元素填入相应位置
  32. arr[i] = temp;
  33. //此时的i即为基准元素的位置
  34. //对基准元素的左边子区间进行相似的快速排序
  35. quickSort(arr,begin,i-1);
  36. //对基准元素的右边子区间进行相似的快速排序
  37. quickSort(arr,i+1,end);
  38. }
  39. //如果区间只有一个数,则返回
  40. else
  41. return;
  42. }
  43. int main(void)
  44. {
  45. int num[12] = {23,45,17,11,13,89,72,26,3,17,11,13};
  46. int n = 12;
  47. quickSort(num,0,n-1);
  48. printf("排序后的数组为:\n");
  49. for(int i=0;i<n;i++)
  50. printf("%d ", num[i]);
  51. printf("\n");
  52. return 0;
  53. }

测试结果:

快速排序为什么要从基准数的对面开始移动?

以自然序排序为例
如果选取最左边的数arr[left]作为基准数,那么先从右边开始可保证i,j在相遇时,相遇数是小于基准数的,交换之后temp所在位置的左边都小于temp。但先从左边开始,相遇数是大于基准数的,无法满足temp左边的数都小于它。所以进行扫描,要从基准数的对面开始。

可以思考一下这幅图和上面逻辑的相似之处

一个堆排序的C语言实现:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. static unsigned int input[] = {1, 3, 4, 5, 2, 6, 9, 7, 8, 0};
  4. void heap_adjust(unsigned int *data, int parent, int length)
  5. {
  6. unsigned int temp = data[parent];
  7. unsigned int child = 2 * parent + 1;
  8. while(child < length)
  9. {
  10. if((child + 1 < length) && input[child] < input[child + 1])
  11. {
  12. child ++;
  13. }
  14. if(temp >= input[child])
  15. {
  16. break;
  17. }
  18. input[parent] = input[child];
  19. parent = child;
  20. child = 2 * child + 1;
  21. }
  22. input[parent] = temp;
  23. }
  24. static void dump(int time, unsigned int *buf)
  25. {
  26. int i;
  27. printf("\ntimes %d: ", time);
  28. for (i = 0; i < 10; i ++)
  29. {
  30. printf("%d ", buf[i]);
  31. }
  32. //printf("\n");
  33. }
  34. int main(void)
  35. {
  36. int i;
  37. for(i = (sizeof(input)/sizeof(input[0])) / 2; i >= 0; i --)
  38. {
  39. heap_adjust(input, i, sizeof(input)/sizeof(input[0]));
  40. }
  41. for(i = (sizeof(input)/sizeof(input[0])) -1; i > 0; i --)
  42. {
  43. int temp = input[i];
  44. input[i] = input[0];
  45. input[0] = temp;
  46. heap_adjust(input, 0, i);
  47. dump(10 - i, input);
  48. }
  49. printf("\n");
  50. return 0;
  51. }
  1. czl@czl-VirtualBox:~/paixu$ ./a.out
  2. times 1: 8 7 6 5 2 1 4 3 0 9
  3. times 2: 7 5 6 3 2 1 4 0 8 9
  4. times 3: 6 5 4 3 2 1 0 7 8 9
  5. times 4: 5 3 4 0 2 1 6 7 8 9
  6. times 5: 4 3 1 0 2 5 6 7 8 9
  7. times 6: 3 2 1 0 4 5 6 7 8 9
  8. times 7: 2 0 1 3 4 5 6 7 8 9
  9. times 8: 1 0 2 3 4 5 6 7 8 9
  10. times 9: 0 1 2 3 4 5 6 7 8 9
  11. czl@czl-VirtualBox:~/paixu$

深度有限搜索递归算法

下面的代码会通过block数组将死胡同的路径标出来。

  1. #include <stdio.h>
  2. #include <stdbool.h>
  3. #include <stdlib.h>
  4. int n, m, p, q, min=99999999;
  5. int a[5][4], book[5][4], block[5][4];
  6. #define FAKE_BLOCK 2
  7. bool dfs(int prex, int prey, int x, int y, int step)
  8. {
  9. int next[4][2] = \
  10. {{0, 1}, //left
  11. {1, 0}, //down
  12. {0, -1}, //right
  13. {-1, 0}};//up
  14. int tx, ty, k;
  15. if(x == p && y == q)
  16. {
  17. printf("%s line %d, step %d.\n", __func__, __LINE__, step);
  18. if(step < min)
  19. min = step;
  20. return true;
  21. }
  22. bool status = false;
  23. for(k = 0; k <= 3; k ++ )
  24. {
  25. tx = x + next[k][0];
  26. ty = y + next[k][1];
  27. if(tx < 0 || tx >= n || ty < 0 || ty >= m)
  28. continue;
  29. if(a[tx][ty] == 0 && book[tx][ty] == FAKE_BLOCK &&!(tx==prex && ty==prey))
  30. {
  31. status = true;
  32. continue;
  33. }
  34. else if(a[tx][ty] == 0 && book[tx][ty] == FAKE_BLOCK)
  35. {
  36. continue;
  37. }
  38. if(a[tx][ty] == 0 && book[tx][ty] == 0)
  39. {
  40. book[tx][ty] = FAKE_BLOCK;
  41. if (true == dfs(x, y, tx, ty, step + 1))
  42. {
  43. status = true;
  44. }
  45. else
  46. {
  47. }
  48. book[tx][ty] = 0;
  49. }
  50. }
  51. if(status == true)
  52. {
  53. printf("x=%d,y=%d.\n", x, y);
  54. }
  55. else
  56. {
  57. printf("[%d,%d]->[%d,%d] block.\n", prex, prey, x, y);
  58. block[x][y] = 1;
  59. }
  60. return status;
  61. }
  62. int main(void)
  63. {
  64. int i, j, startx, starty;
  65. n = 5;
  66. m = 4;
  67. startx = 0;
  68. starty = 0;
  69. p = 3;
  70. q = 2;
  71. a[0][0] = 0; a[0][1] = 0; a[0][2] = 1; a[0][3] = 0;
  72. a[1][0] = 0; a[1][1] = 0; a[1][2] = 0; a[1][3] = 1;
  73. a[2][0] = 0; a[2][1] = 0; a[2][2] = 1; a[2][3] = 0;
  74. a[3][0] = 0; a[3][1] = 1; a[3][2] = 0; a[3][3] = 0;
  75. a[4][0] = 0; a[4][1] = 0; a[4][2] = 0; a[4][3] = 1;
  76. book[startx][starty] = FAKE_BLOCK;
  77. dfs(-1, -1, startx, starty, 0);
  78. printf("%d\n", min);
  79. printf("=========================================\n");
  80. for (i = 0; i < n; i ++)
  81. {
  82. for(j = 0; j < m; j ++)
  83. {
  84. printf("%d ", a[i][j]);
  85. }
  86. printf("\n");
  87. }
  88. printf("=========================================\n");
  89. printf("=========================================\n");
  90. for (i = 0; i < n; i ++)
  91. {
  92. for(j = 0; j < m; j ++)
  93. {
  94. printf("%d ", book[i][j]);
  95. }
  96. printf("\n");
  97. }
  98. printf("=========================================\n");
  99. printf("=========================================\n");
  100. for (i = 0; i < n; i ++)
  101. {
  102. for(j = 0; j < m; j ++)
  103. {
  104. printf("%d ", block[i][j]);
  105. }
  106. printf("\n");
  107. }
  108. printf("=========================================\n");
  109. return 0;
  110. }

运行结果:

以上代码可能还有些问题:

走法讲解:

使用栈实现的迷宫算法:

  1. //迷宫问题
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #define m 9
  5. #define n 9
  6. #define MAXSIZE 100
  7. //迷宫问题
  8. //定义移动位置 ,其中
  9. typedef struct{
  10. int x,y;
  11. }item;
  12. //定义一个数据类型为dataType,在栈里面存在此数据
  13. //主要作为迷宫移动位置的临时存放点,其中x为当前位置的横坐标,y为当前位置的纵坐标
  14. //d为 搜索的次数(方向)
  15. typedef struct{
  16. int x,y,d;
  17. }dataType;
  18. //定义一个栈
  19. typedef struct{
  20. dataType data[MAXSIZE];
  21. int top;
  22. }list,*pList;
  23. //创建栈
  24. pList initList(){
  25. pList p;
  26. p = (pList)malloc(sizeof(list));
  27. if(p){
  28. p->top = -1;
  29. }
  30. return p;
  31. }
  32. //判断栈是否为空
  33. int isEmpty(pList p){
  34. if(p->top==-1){
  35. return 1;//如果是空栈就返回1
  36. }else{
  37. return 0;
  38. }
  39. }
  40. //压栈
  41. int pushList(pList p,dataType data){
  42. if(p->top==MAXSIZE-1){//如果栈超出了大小,返回0
  43. return 0;
  44. }
  45. p->top++;
  46. p->data[p->top] = data;//压栈操作
  47. return 1;//压栈成功,返回1
  48. }
  49. //弹栈
  50. int popList(pList p,dataType *data){
  51. if(isEmpty(p)){
  52. return 0;//如果是空栈,就不弹,直接返回0
  53. }else{
  54. *data = p->data[p->top];
  55. p->top--;
  56. return 1;
  57. }
  58. }
  59. //销毁栈
  60. void destory(pList *p){
  61. if(*p){
  62. free(*p);
  63. }
  64. *p = NULL;
  65. return;
  66. }
  67. int mazePath(int maze[][n+2],item move[],int x0,int y0){//maze表示一个迷宫的数组,move表示当前探索,x0,y0表示初始位置
  68. pList p;//定义栈
  69. dataType temp;//定义临时位置
  70. int x,y,d,i,j;//x,y用来存放临时位置的角标,d表示临时的探索次数,i,j所在位置的迷宫角标
  71. p = initList();//创建栈
  72. if(!p){//如果创建失败
  73. printf("创建栈失败");
  74. return 0;
  75. }
  76. //初始化走过的位置
  77. temp.x = x0;
  78. temp.y = y0;
  79. temp.d = -1;
  80. //把迷宫入口压栈
  81. pushList(p,temp);
  82. //当栈里面不为空时
  83. while(!isEmpty(p)){
  84. popList(p,&temp);//弹栈
  85. x = temp.x;
  86. y = temp.y;
  87. d = temp.d+1;//给d+1,让其进行第一次探索
  88. while(d<4){//四次探索
  89. i = x+move[d].x;//原来的位置加上探索的位置
  90. j = y+move[d].y;
  91. //当某条路是通路的时候
  92. if(maze[i][j]==0){//表示此路可走
  93. //使用temp来保存路径
  94. temp.x = x;
  95. temp.y = y;
  96. temp.d = d;
  97. //将路径压栈
  98. pushList(p,temp);
  99. //x、y来保存当前新的路径
  100. x = i;
  101. y = j;
  102. maze[x][y] = -1;//把走过的路径的值设为-1
  103. if(x==m && y==n){//判断是否走到头,如果走到头
  104. while(!isEmpty(p)){//如果栈不为空
  105. popList(p,&temp);//弹栈
  106. printf("(%d,%d,%d),<-",temp.x,temp.y,temp.d);//打印路径
  107. }
  108. printf("origin\n");
  109. //程序结束,销毁栈
  110. destory(&p);
  111. return 1;
  112. }else{//如果能走通,但是却没有走完迷宫,把d置为0
  113. d = 0;
  114. }
  115. } else{//如果路不通,换个方向在进行探索
  116. d++;
  117. }
  118. }
  119. }
  120. //如果最后都没找到,说明迷宫没有通路
  121. destory(&p);
  122. return 0;
  123. }
  124. void main(){
  125. item move[4];//定义一个控制探索路径的移动数组
  126. //定义迷宫数组
  127. int maze[11][11]={
  128. {1,1,1,1,1,1,1,1,1,1,1},
  129. {1,0,0,0,1,0,1,1,1,0,1},
  130. {1,0,1,0,0,0,0,1,0,1,1},
  131. {1,0,0,1,0,0,0,1,0,0,1},
  132. {1,1,0,1,0,1,0,1,0,1,1},
  133. {1,0,1,0,1,0,0,1,0,0,1},
  134. {1,0,0,0,0,0,1,0,1,0,1},
  135. {1,1,1,1,0,1,0,0,0,0,1},
  136. {1,0,0,1,0,0,0,1,0,1,1},
  137. {1,0,0,0,0,1,0,1,0,0,1},
  138. {1,1,1,1,1,1,1,1,1,1,1}
  139. };
  140. //定义第一次移动 ,方向为北
  141. move[0].x = 0;
  142. move[0].y = 1;
  143. //定义第二次移动,方向为南
  144. move[1].x = 0;
  145. move[1].y = -1;
  146. //规定第三次移动,方向为东
  147. move[2].x = 1;
  148. move[2].y = 0;
  149. //规定第三次移动,方向为西
  150. move[3].x = -1;
  151. move[3].y = 0;
  152. mazePath(maze,move,1,1);
  153. }

运行:

冒泡排序:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int main(void)
  4. {
  5. int a[10];
  6. int i = 0;
  7. for(i = 0; i < 10; i ++)
  8. {
  9. a[i] = 10-i;
  10. }
  11. for(i = 0; i < 10; i ++)
  12. {
  13. printf("a[%d] = %d.\n", i, a[i]);
  14. }
  15. printf("=======================================================\n");
  16. int j;
  17. for (j = 9; j > 0; j --)
  18. {
  19. for(i = 0; i < j; i ++)
  20. {
  21. if(a[i] > a[i+1])
  22. {
  23. int tmp;
  24. tmp = a[i + 1];
  25. a[i+1] = a[i];
  26. a[i] = tmp;
  27. }
  28. }
  29. }
  30. for(i = 0; i < 10; i ++)
  31. {
  32. printf("a[%d] = %d.\n", i, a[i]);
  33. }
  34. return 0;
  35. }

时间复杂度和空间复杂度分析:

对于N个数据,外循环N-1次,内循环次数依赖于外循环的记数,一共为N-1+N-2+...+1 = N(N-1)/2

次,如果最差情况下,每次都会执行交换,包含三次赋值,则复杂度为 3N(N-1)/2,所以,冒泡排序:

最优的时间复杂度为:O( n^2 ) ;
最差的时间复杂度为:O( n^2 );
平均的时间复杂度为:O( n^2 );

有的说 O(n),下面会分析这种情况,修改程序,当检测到当前循环不需要交换的时候,说明都是正序,这个时候直接跳出循环:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int main(void)
  4. {
  5. int a[10];
  6. int flag = 1;
  7. int i = 0;
  8. for(i = 0; i < 10; i ++)
  9. {
  10. /*a[i] = 10-i;*/
  11. a[i] = i;
  12. }
  13. for(i = 0; i < 10; i ++)
  14. {
  15. printf("a[%d] = %d.\n", i, a[i]);
  16. }
  17. printf("=======================================================\n");
  18. int j;
  19. for (j = 9; j > 0; j --)
  20. {
  21. flag = 1;
  22. for(i = 0; i < j; i ++)
  23. {
  24. if(a[i] > a[i+1])
  25. {
  26. int tmp;
  27. tmp = a[i + 1];
  28. a[i+1] = a[i];
  29. a[i] = tmp;
  30. flag = 0;
  31. }
  32. }
  33. if(flag) break;
  34. }
  35. for(i = 0; i < 10; i ++)
  36. {
  37. printf("a[%d] = %d.\n", i, a[i]);
  38. }
  39. return 0;
  40. }

空间复杂度好说了,也就是TMP占用的空间,理想情况不需要交换,空间复杂度为0,最差的时候也仅仅是需要1个TMP的空间,也即是O(1).

关于循环条件的两种情况:

冒泡排序的变种奇偶排序

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. void swap(int *array, int j, int k)
  4. {
  5. int temp = array[j];
  6. array[j] = array[k];
  7. array[k] = temp;
  8. }
  9. void scan(int *array, int j)
  10. {
  11. while(j < 9)
  12. {
  13. if(array[j] > array[j + 1])
  14. {
  15. swap(array, j, j + 1);
  16. }
  17. j += 2;
  18. }
  19. return;
  20. }
  21. void print_array(int *array, int count)
  22. {
  23. int i;
  24. for(i = 0; i < count; i ++)
  25. printf(" %d ", array[i]);
  26. printf("\n");
  27. }
  28. int main(void)
  29. {
  30. int i;
  31. int array[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
  32. print_array(array, 10);
  33. for(i = 0; i < 10; i += 2)
  34. {
  35. int j = 0;
  36. scan(array, j);
  37. print_array(array, 10);
  38. j = 1;
  39. scan(array, j);
  40. print_array(array, 10);
  41. }
  42. return 0;
  43. }

run:

  1. ~/czl$ ./a.out
  2. 9 8 7 6 5 4 3 2 1 0
  3. 8 9 6 7 4 5 2 3 0 1
  4. 8 6 9 4 7 2 5 0 3 1
  5. 6 8 4 9 2 7 0 5 1 3
  6. 6 4 8 2 9 0 7 1 5 3
  7. 4 6 2 8 0 9 1 7 3 5
  8. 4 2 6 0 8 1 9 3 7 5
  9. 2 4 0 6 1 8 3 9 5 7
  10. 2 0 4 1 6 3 8 5 9 7
  11. 0 2 1 4 3 6 5 8 7 9
  12. 0 1 2 3 4 5 6 7 8 9
  13. ~/czl$

奇偶排序的GPU实现版本:

  1. #include <cuda_runtime.h>
  2. #include <device_launch_parameters.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <time.h>
  6. #include <unistd.h>
  7. #define MATRIX_M 16
  8. #define MATRIX_N 16
  9. void init_cuda(void)
  10. {
  11. int count, dev;
  12. int i;
  13. cudaDeviceProp prop;
  14. cudaGetDeviceCount(&count);
  15. if(count == 0) {
  16. fprintf(stderr, "there is no cuda device.\n");
  17. return;
  18. } else {
  19. cudaGetDevice(&dev);
  20. fprintf(stdout,"there are %d cudda device found, id %d.\n", count, dev);
  21. }
  22. for(i = 0; i < count; i ++) {
  23. printf("===============================Device %d==================================\n", i);
  24. if(cudaGetDeviceProperties(&prop, i) == cudaSuccess) {
  25. printf("%s\n", prop.name);
  26. printf("Total global memory: %ld Bytes\n", prop.totalGlobalMem);
  27. printf("Max shareable memory per block %ld Bytes.\n", prop.sharedMemPerBlock);
  28. printf("Maximum registers per block: %d\n", prop.regsPerBlock);
  29. printf("Wrap Size %d.\n", prop.warpSize);
  30. printf("Maximum threads per block %d.\n", prop.maxThreadsPerBlock);
  31. printf("Maximum block dimensions [%d, %d, %d].\n", prop.maxThreadsDim[0], prop.maxThreadsDim[1], prop.maxThreadsDim[2]);
  32. printf("Maximum grid dimensions [%d, %d, %d].\n", prop.maxGridSize[0], prop.maxGridSize[1], prop.maxGridSize[2]);
  33. printf("Total constant memory: %ld.\n", prop.totalConstMem);
  34. printf("Support compute Capability: %d.%d.\n", prop.major, prop.minor);
  35. printf("Kernel Frequency %d kHz.\n", prop.clockRate);
  36. printf("Number of MultProcessors %d.\n", prop.multiProcessorCount);
  37. printf("Is MultiGPU: %s.\n", prop.isMultiGpuBoard ? "Yes" : "No");
  38. printf("L2 Cache Size: %d Bytes.\n", prop.l2CacheSize);
  39. printf("Memory Bus Width: %d.\n", prop.memoryBusWidth);
  40. printf("ECC status: %s.\n", prop.ECCEnabled? "Enable" : "Disable");
  41. }
  42. printf("=========================================================================\n");
  43. }
  44. cudaSetDevice(1);
  45. }
  46. void init_array(int *data, int n)
  47. {
  48. int i = 0;
  49. for(i = 0; i < n; i ++){
  50. data[i] = n - i;
  51. }
  52. }
  53. void print_array(int *data, int n)
  54. {
  55. int i;
  56. for(i = 0; i < n; i ++){
  57. if(i % 10 == 0) printf("\n");
  58. printf("%d\t", data[i]);
  59. }
  60. printf("\n");
  61. }
  62. #define N 100
  63. __global__ static void sort_array(int *array)
  64. {
  65. int tid = threadIdx.x;
  66. int a;
  67. int i = 0;
  68. for(i = 0; i < N/2; i ++){
  69. if((2 * tid + 1) < N) {
  70. if(array[2*tid] > array[2*tid + 1]) {
  71. a = array[2 * tid];
  72. array[2 * tid] = array[2 * tid + 1];
  73. array[2 * tid +1] = a;
  74. }
  75. }
  76. __syncthreads();
  77. if((2 * tid + 2) < N) {
  78. if(array[2 * tid + 1] > array[2 * tid + 2]) {
  79. a = array[2 * tid + 1];
  80. array[2 * tid +1] = array[2 * tid + 2];
  81. array[2 * tid + 2] = a;
  82. }
  83. }
  84. __syncthreads();
  85. }
  86. }
  87. int main(void)
  88. {
  89. int *pdataA;
  90. int *pdata_gpuA;
  91. init_cuda();
  92. cudaMallocHost((void**)&pdataA, N * sizeof(int));
  93. if(pdataA == NULL) {
  94. fprintf(stderr, "fatal error, malloc host buffer failure.\n");
  95. return -1;
  96. }
  97. cudaHostGetDevicePointer((void**)&pdata_gpuA, (void*)pdataA, 0);
  98. if(pdata_gpuA == NULL) {
  99. fprintf(stderr, "fatal error, get device ptr failure.\n");
  100. return -1;
  101. }
  102. printf("%s line %d, pdataA = %p, pdata_gpuA = %p.\n", __func__, __LINE__, pdataA, pdata_gpuA);
  103. if(pdataA != pdata_gpuA) {
  104. printf("%s line %d, not uma address space.\n", __func__, __LINE__);
  105. }
  106. init_array(pdataA, N);
  107. print_array(pdataA,N);
  108. dim3 blocksize(N/2, 1, 1);
  109. dim3 gridsize(1, 1, 1);
  110. sort_array<<< gridsize, blocksize >>>(pdata_gpuA);
  111. cudaDeviceSynchronize();
  112. print_array(pdataA,N);
  113. cudaFree(pdataA);
  114. return 0;
  115. }

二分排序

一把撸成的二分排序。

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. int *binary_sort(int *array, int n)
  5. {
  6. int *p = malloc(n * sizeof(int));
  7. if(p == NULL)
  8. {
  9. printf("%s line %d.\n", __func__, __LINE__);
  10. return NULL;
  11. }
  12. memset(p, 0x00, sizeof(int)*n);
  13. if (n == 1)
  14. {
  15. p[0] = array[0];
  16. return p;
  17. }
  18. int n1,n2;
  19. if(n % 2 == 0)
  20. {
  21. n1 = n2 = n/2;
  22. }
  23. else
  24. {
  25. n1 = n/2;
  26. n2 = n1 + 1;
  27. }
  28. if((n1 + n2) != n)
  29. {
  30. printf("fatal error.\n");
  31. return NULL;
  32. }
  33. int *pre = binary_sort(array, n1);
  34. int *pos = binary_sort(array + n1, n2);
  35. int i = 0;
  36. int j = 0;
  37. int s = 0;
  38. int tmp;
  39. for(s = 0; s < n; s ++)
  40. {
  41. if(i < n1 && j < n2)
  42. {
  43. if( pre[i] <= pos[j] )
  44. {
  45. tmp = pre[i];
  46. i ++;
  47. }
  48. else
  49. {
  50. tmp = pos[j];
  51. j ++;
  52. }
  53. }
  54. else
  55. {
  56. if(i >= n1)
  57. {
  58. tmp = pos[j]; j ++;
  59. }
  60. else
  61. {
  62. tmp = pre[i]; i ++;
  63. }
  64. }
  65. p[s] = tmp;
  66. }
  67. free(pre);
  68. free(pos);
  69. pre = pos = NULL;
  70. return p;
  71. }
  72. #define NUM 800
  73. int main(void)
  74. {
  75. int i;
  76. int array[NUM];
  77. for(i = 0; i < NUM; i ++)
  78. {
  79. array[i] = NUM-i;
  80. }
  81. for(i = 0; i < NUM; i ++)
  82. {
  83. printf("array[%d] = %d.\n", i, array[i]);
  84. }
  85. int *p = binary_sort(array, NUM);
  86. for(i = 0; i < NUM; i ++)
  87. {
  88. printf("p[%d] = %d.\n", i, p[i]);
  89. }
  90. free(p);
  91. return 0;
  92. }

归并排序复杂度分析:

\boldsymbol{O(N)=2 \cdot O(N/2) + N = 4\cdot O(N/4) + 2N = 8 \cdot O(N/8) + 3N=\cdots =N\cdot O(1) + log^N_2 \cdot N = N+N\cdot log^N_2}

所以,复杂度为

O(N\cdot log^N_2)


全排列程序:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define NUMS 10
  4. static int num[NUMS];
  5. static int flag[NUMS];
  6. static int res[NUMS];
  7. static int depth = 0;
  8. static long total = 0;
  9. void total_pailie(void)
  10. {
  11. int i;
  12. if(depth == NUMS)
  13. {
  14. int j = 0;
  15. for (j = 0; j < NUMS ;j ++)
  16. {
  17. printf("%d ", res[j]);
  18. }
  19. total ++;
  20. printf("\n");
  21. }
  22. for(i = 0; i < NUMS; i ++)
  23. {
  24. if(flag[i] == 1) continue;
  25. flag[i] = 1;
  26. res[depth] = num[i];
  27. depth ++;
  28. total_pailie();
  29. depth --;
  30. flag[i] = 0;
  31. }
  32. }
  33. int main(void)
  34. {
  35. int i;
  36. for(i = 0; i < NUMS; i ++)
  37. {
  38. num[i] = i;
  39. flag[i] = 0;
  40. res[i] = 0;
  41. }
  42. total_pailie();
  43. printf("%s line %d, total %ld.\n", __func__, __LINE__, total);
  44. return 0;
  45. }

10的阶乘:

另一种方式,由于内部已经包含了排列组合公式,不是一个好方案,相当于手工代替机器做了很多额外的工作:

如何判断一个链表是否存在循环?

快慢指针的方式,代码如下:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct node head;
  4. struct node *phead;
  5. struct node {
  6. struct node *next;
  7. int val;
  8. };
  9. void add_node(struct node *n)
  10. {
  11. struct node *no = phead;
  12. while(no->next) no = no->next;
  13. no->next = n;
  14. return;
  15. }
  16. int check_loop(void)
  17. {
  18. int ret = 0;
  19. struct node *n1, *n2;
  20. n1 = n2 = phead;
  21. while(n1 && n2)
  22. {
  23. n1 = n1->next;
  24. if(!n1) {
  25. ret = 0;
  26. printf("exit in zero.\n");
  27. break;
  28. }
  29. n2 = n2->next;
  30. if(!n2) {
  31. ret = 0;
  32. printf("exit in one.\n");
  33. break;
  34. }
  35. n2 = n2->next;
  36. if(n1 == n2) {
  37. ret = 1;
  38. break;
  39. }
  40. }
  41. if(!n1)
  42. {
  43. printf("n1 is null.\n");
  44. }
  45. if(!n2)
  46. {
  47. printf("n2 is null.\n");
  48. }
  49. printf("exit in two.\n");
  50. return ret;
  51. }
  52. int main(void)
  53. {
  54. int i;
  55. struct node array[100];
  56. struct node *no;
  57. phead = &head;
  58. head.next = NULL;
  59. head.val = 255;
  60. for(i = 0; i < 100; i ++)
  61. {
  62. array[i].next = NULL;
  63. array[i].val = i;
  64. add_node(&array[i]);
  65. }
  66. no = phead;
  67. while(no)
  68. {
  69. printf("%s line %d, val %d.\n", __func__, __LINE__, no->val);
  70. no = no->next;
  71. }
  72. // add loop node.
  73. add_node(&array[6]);
  74. #if 0
  75. no = phead;
  76. while(no)
  77. {
  78. printf("%s line %d, val %d.\n", __func__, __LINE__, no->val);
  79. no = no->next;
  80. }
  81. #endif
  82. printf("%s line %d, checkloop %s.\n", __func__, __LINE__, check_loop() ? "have loop" : "no loop");
  83. return 0;
  84. }

证明,假设当前1倍速节点的位置为(n+k),则二倍速节点的位置为(2n+s).则最差情况下,存在着(n+k)*(2n+s)步,使两个节点同时达到这里。得证。对于不同速度遍历的两个指针,假如速度为N和M,则最差在公约数NM时相遇。

快速排序为何从GUARD VALUE的对向开始验证程序

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. //快速排序算法(从小到大)
  5. //arr:需要排序的数组,begin:需要排序的区间左边界,end:需要排序的区间的右边界
  6. void quickSort(int *arr,int begin,int end)
  7. {
  8. //如果区间不只一个数
  9. if(begin < end)
  10. {
  11. int temp = arr[begin]; //将区间的第一个数作为基准数
  12. int i = begin; //从左到右进行查找时的“指针”,指示当前左位置
  13. int j = end; //从右到左进行查找时的“指针”,指示当前右位置
  14. //不重复遍历
  15. while(i < j)
  16. {
  17. int k;
  18. //当右边的数大于基准数时,略过,继续向左查找
  19. //不满足条件时跳出循环,此时的j对应的元素是小于基准元素的
  20. while(i<j && arr[j] > temp)
  21. j--;
  22. while(i<j && arr[i] <= temp)
  23. i++;
  24. k = arr[j];
  25. arr[j] = arr[i];
  26. arr[i] =k;
  27. }
  28. for(int s = begin; s < j; s ++)
  29. arr[s] = arr[s+1];
  30. //将基准元素填入相应位置
  31. arr[j] = temp;
  32. //此时的i即为基准元素的位置
  33. //对基准元素的左边子区间进行相似的快速排序
  34. quickSort(arr,begin,i-1);
  35. //对基准元素的右边子区间进行相似的快速排序
  36. quickSort(arr,i+1,end);
  37. }
  38. //如果区间只有一个数,则返回
  39. else
  40. return;
  41. }
  42. int main(void)
  43. {
  44. int num[12] = {23,45,17,11,13,89,72,26,3,17,11,13};
  45. //int num[12] = {13,12,11,10,8,7,6,5,4,3,2,1};
  46. int n = 12;
  47. quickSort(num,0,n-1);
  48. printf("排序后的数组为:\n");
  49. for(int i=0;i<n;i++)
  50. printf("%d ", num[i]);
  51. printf("\n");
  52. return 0;
  53. }

快速排序是一种分治算法,它的核心思想是将待排序序列分成两个子序列,其中一个子序列的元素都比另一个子序列的原则小,然后对这两个子序列进行递归排序,直到整个序列有序。在这个过程中,需要一个基准数,通常选择序列的第一个或者最后一个元素作为基准。

从基准数的对面开始移移指针,是为了保证算法的正确性。如果从基准数的同侧开始移动指针,可能会出现左右指针相遇时,集注疏左侧仍然有比基准数大的情况,导致排序结果不正确,从基准数对面开始移动指针,可以避免这种情况。下面的程序展示了从左边开始动,需要做一次相遇时的大小判断才能正确排序:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. static void dump_array(int *arr, int n)
  5. {
  6. for(int i=0;i<n;i++)
  7. printf("%d ", arr[i]);
  8. printf("\n");
  9. }
  10. //快速排序算法(从小到大)
  11. //arr:需要排序的数组,begin:需要排序的区间左边界,end:需要排序的区间的右边界
  12. void quickSort(int *arr,int begin,int end)
  13. {
  14. //如果区间不只一个数
  15. if(begin < end)
  16. {
  17. int temp = arr[begin]; //将区间的第一个数作为基准数
  18. int i = begin; //从左到右进行查找时的“指针”,指示当前左位置
  19. int j = end; //从右到左进行查找时的“指针”,指示当前右位置
  20. //不重复遍历
  21. while(i < j)
  22. {
  23. int k;
  24. //当右边的数大于基准数时,略过,继续向左查找
  25. //不满足条件时跳出循环,此时的j对应的元素是小于基准元素的
  26. while(i<j && arr[i] <= temp)
  27. i++;
  28. while(i<j && arr[j] >= temp)
  29. j--;
  30. k = arr[j];
  31. arr[j] = arr[i];
  32. arr[i] =k;
  33. dump_array(arr, 12);
  34. }
  35. int pos = j;
  36. if(arr[i] > temp) {
  37. pos = i - 1;
  38. }
  39. for(int s = begin; s < pos; s ++)
  40. arr[s] = arr[s+1];
  41. //将基准元素填入相应位置
  42. arr[pos] = temp;
  43. printf("%s line %d, i %d, j %d.\n", __func__, __LINE__, i, j);
  44. dump_array(arr, 12);
  45. //此时的i即为基准元素的位置
  46. //对基准元素的左边子区间进行相似的快速排序
  47. quickSort(arr,begin,pos-1);
  48. //对基准元素的右边子区间进行相似的快速排序
  49. quickSort(arr,pos+1,end);
  50. }
  51. //如果区间只有一个数,则返回
  52. else
  53. return;
  54. }
  55. int main(void)
  56. {
  57. int num[12] = {23,45,17,11,13,89,72,26,3,17,11,13};
  58. //int num[12] = {13,12,11,10,8,7,6,5,4,3,2,1};
  59. int n = 12;
  60. quickSort(num,0,n-1);
  61. printf("排序后的数组为:\n");
  62. dump_array(num, 12);
  63. return 0;
  64. }

逆序排同样要从对对向开始:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. static void dump_array(int *arr, int n)
  5. {
  6. for(int i=0;i<n;i++)
  7. printf("%d ", arr[i]);
  8. printf("\n");
  9. }
  10. //快速排序算法(从小到大)
  11. //arr:需要排序的数组,begin:需要排序的区间左边界,end:需要排序的区间的右边界
  12. void quickSort(int *arr,int begin,int end)
  13. {
  14. //如果区间不只一个数
  15. if(begin < end)
  16. {
  17. int temp = arr[begin]; //将区间的第一个数作为基准数
  18. int i = begin; //从左到右进行查找时的“指针”,指示当前左位置
  19. int j = end; //从右到左进行查找时的“指针”,指示当前右位置
  20. //不重复遍历
  21. while(i < j)
  22. {
  23. int k;
  24. //当右边的数大于基准数时,略过,继续向左查找
  25. //不满足条件时跳出循环,此时的j对应的元素是小于基准元素的
  26. //while(i<j && arr[i] <= temp)
  27. while(i<j && arr[i] >= temp)
  28. i++;
  29. //while(i<j && arr[j] > temp)
  30. while(i<j && arr[j] <= temp)
  31. j--;
  32. k = arr[j];
  33. arr[j] = arr[i];
  34. arr[i] =k;
  35. dump_array(arr, 12);
  36. }
  37. int pos = j;
  38. if(arr[i] < temp) {
  39. pos = i - 1;
  40. }
  41. for(int s = begin; s < pos; s ++)
  42. arr[s] = arr[s+1];
  43. //将基准元素填入相应位置
  44. arr[pos] = temp;
  45. printf("%s line %d, i %d, j %d.\n", __func__, __LINE__, i, j);
  46. dump_array(arr, 12);
  47. //此时的i即为基准元素的位置
  48. //对基准元素的左边子区间进行相似的快速排序
  49. quickSort(arr,begin,pos-1);
  50. //对基准元素的右边子区间进行相似的快速排序
  51. quickSort(arr,pos+1,end);
  52. }
  53. //如果区间只有一个数,则返回
  54. else
  55. return;
  56. }
  57. int main(void)
  58. {
  59. int num[12] = {23,45,17,11,13,89,72,26,3,17,11,13};
  60. //int num[12] = {13,12,11,10,8,7,6,5,4,3,2,1};
  61. int n = 12;
  62. quickSort(num,0,n-1);
  63. printf("排序后的数组为:\n");
  64. dump_array(num, 12);
  65. return 0;
  66. }

采用对抗式算法,用前面的程序进行排列组合,然后用快速排序重新排序,验证排序算法的正确性!

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #define NUMS 20
  5. static int num[NUMS];
  6. static int flag[NUMS];
  7. static int res[NUMS];
  8. static int depth = 0;
  9. static long total = 0;
  10. //快速排序算法(从小到大)
  11. //arr:需要排序的数组,begin:需要排序的区间左边界,end:需要排序的区间的右边界
  12. void quick_sort(int *arr,int begin,int end)
  13. {
  14. //如果区间不只一个数
  15. if(begin < end)
  16. {
  17. int temp = arr[begin]; //将区间的第一个数作为基准数
  18. int i = begin; //从左到右进行查找时的“指针”,指示当前左位置
  19. int j = end; //从右到左进行查找时的“指针”,指示当前右位置
  20. //不重复遍历
  21. while(i < j)
  22. {
  23. //当右边的数大于基准数时,略过,继续向左查找
  24. //不满足条件时跳出循环,此时的j对应的元素是小于基准元素的
  25. while(i<j && arr[j] > temp)
  26. j--;
  27. //将右边小于等于基准元素的数填入右边相应位置
  28. arr[i] = arr[j];
  29. //当左边的数小于等于基准数时,略过,继续向右查找
  30. //(重复的基准元素集合到左区间)
  31. //不满足条件时跳出循环,此时的i对应的元素是大于等于基准元素的
  32. while(i<j && arr[i] <= temp)
  33. i++;
  34. //将左边大于基准元素的数填入左边相应位置
  35. arr[j] = arr[i];
  36. }
  37. //将基准元素填入相应位置
  38. arr[i] = temp;
  39. //此时的i即为基准元素的位置
  40. //对基准元素的左边子区间进行相似的快速排序
  41. quick_sort(arr,begin,i-1);
  42. //对基准元素的右边子区间进行相似的快速排序
  43. quick_sort(arr,i+1,end);
  44. }
  45. //如果区间只有一个数,则返回
  46. else
  47. return;
  48. }
  49. //快速排序算法(从小到大)
  50. //arr:需要排序的数组,begin:需要排序的区间左边界,end:需要排序的区间的右边界
  51. void quickSort(int *arr,int begin,int end)
  52. {
  53. //如果区间不只一个数
  54. if(begin < end)
  55. {
  56. int temp = arr[begin]; //将区间的第一个数作为基准数
  57. int i = begin; //从左到右进行查找时的“指针”,指示当前左位置
  58. int j = end; //从右到左进行查找时的“指针”,指示当前右位置
  59. //不重复遍历
  60. while(i < j)
  61. {
  62. int k;
  63. //当左边的数小于等于基准数时,略过,继续向右查找
  64. //(重复的基准元素集合到左区间)
  65. //不满足条件时跳出循环,此时的i对应的元素是大于等于基准元素的
  66. while(i<j && arr[i] <= temp)
  67. i++;
  68. //当右边的数大于基准数时,略过,继续向左查找
  69. //不满足条件时跳出循环,此时的j对应的元素是小于基准元素的
  70. while(i<j && arr[j] >= temp)
  71. j--;
  72. //交换j,i;
  73. k = arr[j];
  74. arr[j] = arr[i];
  75. arr[i] = k;
  76. }
  77. int pos = j;
  78. if(arr[i] > temp) {
  79. pos = i - 1;
  80. }
  81. for(int s = begin; s < pos; s ++)
  82. arr[s] = arr[s+1];
  83. //将基准元素填入相应位置
  84. //此时的pos即为基准元素的位置
  85. arr[pos] = temp;
  86. //对基准元素的左边子区间进行相似的快速排序
  87. quickSort(arr,begin,pos-1);
  88. //对基准元素的右边子区间进行相似的快速排序
  89. quickSort(arr,pos+1,end);
  90. }
  91. //如果区间只有一个数,则返回
  92. else
  93. return;
  94. }
  95. void total_pailie(void)
  96. {
  97. int i;
  98. if(depth == NUMS)
  99. {
  100. int j = 0;
  101. int *ptemp = malloc(sizeof(int)*NUMS);
  102. memset(ptemp, 0xff, sizeof(int)*NUMS);
  103. for (j = 0; j < NUMS ;j ++) {
  104. //printf("%d ", res[j]);
  105. ptemp[j] = res[j];
  106. }
  107. //quick_sort(ptemp, 0, NUMS-1);
  108. quickSort(ptemp, 0, NUMS-1);
  109. for (j = 0; j < NUMS ;j ++) {
  110. printf("%d ", ptemp[j]);
  111. if(ptemp[j] != j)
  112. {
  113. while(1)
  114. printf("%s line %d. fata error.\n", __func__, __LINE__);
  115. }
  116. }
  117. total ++;
  118. free(ptemp);
  119. printf("\n");
  120. }
  121. for(i = 0; i < NUMS; i ++)
  122. {
  123. if(flag[i] == 1) continue;
  124. flag[i] = 1;
  125. res[depth] = num[i];
  126. depth ++;
  127. total_pailie();
  128. depth --;
  129. flag[i] = 0;
  130. }
  131. }
  132. int main(void)
  133. {
  134. int i;
  135. for(i = 0; i < NUMS; i ++)
  136. {
  137. num[i] = i;
  138. flag[i] = 0;
  139. res[i] = 0;
  140. }
  141. total_pailie();
  142. printf("%s line %d, total %ld.\n", __func__, __LINE__, total);
  143. return 0;
  144. }

以NUMS=12为例,我们对12个数作全排列的结果进行排序,排序进行了12!=479001600,全部排正确,算法稳定运行。

简单的说,如果从同侧开始,则相遇点的数值可能大于基准数,导致需要进行比对会退一位。

最简单的排序算法

那种排序算法最为简单呢,这实际上取决于你对简单的定义,但选择排序很可能是不错的选择,这个算法的思想是不断的找出最小元素,并将其移到左边,你可以使用两个FOR循环加上一个条件交换来实现它,外层循环将过程分成N个阶段,在每个阶段,都会执行内层循环来寻找下一个最小值。

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. void sort(int *array, int len)
  4. {
  5. int i;
  6. int j;
  7. int tmp;
  8. for(i = 0; i < len; i ++) {
  9. for(j = i+1; j < len; j ++) {
  10. if(array[i] > array[j]) {
  11. tmp = array[j];
  12. array[j] = array[i];
  13. array[i] = tmp;
  14. }
  15. }
  16. }
  17. }
  18. int main(void)
  19. {
  20. int i;
  21. int num[10] = {9, 4, 8, 6, 7, 2, 5, 0, 1, 3};
  22. sort(num, 10);
  23. printf("\n");
  24. for(i = 0; i < 10; i ++) {
  25. printf("%d ", num[i]);
  26. }
  27. printf("\n");
  28. return 0;
  29. }

选择排序和插入排序的组合,它们的组合方式确保了只有插入排序起作用。

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. void sort(int *array, int len)
  4. {
  5. int i;
  6. int j;
  7. int tmp;
  8. for(i = 0; i < len; i ++) {
  9. //for(j = 0; j < len; j ++) {
  10. for(j = 0; j < i; j ++) {
  11. if(array[i] > array[j]) {
  12. tmp = array[j];
  13. array[j] = array[i];
  14. array[i] = tmp;
  15. }
  16. }
  17. }
  18. }
  19. int main(void)
  20. {
  21. int i;
  22. int num[10] = {9, 4, 8, 6, 7, 2, 5, 0, 1, 3};
  23. sort(num, 10);
  24. printf("\n");
  25. for(i = 0; i < 10; i ++) {
  26. printf("%d ", num[i]);
  27. }
  28. printf("\n");
  29. return 0;
  30. }

结束!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号