【数据结构】插入排序

前端之家收集整理的这篇文章主要介绍了【数据结构】插入排序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

对于一个int数组,请编写一个插入排序算法,对数组元素排序。
给定一个int数组A及数组的大小n,请返回排序后的数组。
测试样例:
[1,2,3,5,3],6
[1,5]

  1. class InsertionSort {
  2. public:
  3. void swap(int * a,int * b){
  4. int temp = *a;
  5. *a = *b;
  6. *b = temp;
  7. }
  8.  
  9. void print(int * A,int n){
  10. for (int i = 0; i < n; i++)
  11. printf("%d ",A[i]);
  12. printf("\n");
  13. }
  14.  
  15. int* insertionSort(int* A,int n) {
  16. // write code here
  17.  
  18. //index
  19. for (int i = 1; i < n; i++){
  20.  
  21. int current_val = A[i];
  22. int j;
  23. for (j = i; j > 0; j--){
  24. if (current_val < A[j-1]){
  25. A[j] = A[j-1];
  26. }
  27. else{
  28. break;
  29. }
  30. }
  31. A[j] = current_val;
  32. }
  33.  
  34. return A;
  35. }
  36. };

猜你在找的数据结构相关文章