• 排序算法



    1. // sort.cpp : Defines the entry point for the console application.
    2. //
    3. #include "stdafx.h"
    4. #include <iostream>
    5. using namespace std;
    6. void print ( int a[] ,int n )
    7. {
    8. for ( int i=0;i<n;i++) cout<<a[i]<<",";
    9. cout<<endl;
    10. }
    11. // ðÅÝÅÅÐò
    12. void bubble_sort( int a[] , int n )
    13. {
    14. for ( int i=0 ; i < n; i++ ) {
    15. for ( int j=i+1; j< n; j++ ) {
    16. if ( a[i] > a[j] ) {
    17. int tmp = a[i];
    18. a[i] = a[j] ;
    19. a[j] = tmp;
    20. }
    21. }
    22. }
    23. print ( a, 10 );
    24. }
    25. // ²åÈëÅÅÐò
    26. void insert_sort ( int a[] , int n )
    27. {
    28. int b[10] ={0,0,0,0,0,0,0,0,0};
    29. for ( int i = 0; i < n ; i++ ) {
    30. if ( a[i] < b[0] ) {
    31. b[0] = a[i];
    32. for ( int j=1 ; j<i-1; j++ ) b[j] = b[j+1];
    33. }
    34. if( a[i] > b[i-1] ) b[i] = a[i] ;
    35. for ( int j = 0 ; j < i-1 ; j++ ) {
    36. if ( a[i] > b[j] && a[i] < b[j+1] ) {
    37. b[j] = a[i];
    38. for ( int n=j+1; n<j ; n++) b[n] = b[n+1];
    39. break;
    40. }
    41. }
    42. }
    43. print ( b, 10 );
    44. }
    45. // Ñ¡ÔñÅÅÐò
    46. void select_sort ( int a[] , int len )
    47. {
    48. for ( int i = 0 ; i < len ; i++ ) {
    49. for ( int j=i+1; j< len; j++ ) {
    50. if ( a[j] > a[i] ) {
    51. int tmp = a[j] ;
    52. a[j] = a[i];
    53. a[i] = tmp;
    54. }
    55. }
    56. }
    57. print ( a, 10 );
    58. }
    59. // µÝ¹é·Ö×éÅÅÐò
    60. void recursive_group_sort ( int a[] , int left , int right )
    61. {
    62. if ( left == right ) return;
    63. int mid = (right+left)/2;
    64. for( int i=left; i<= mid; i++) {
    65. for( int j=mid+1; j <= right ; j++ ) {
    66. if( a[i] > a[j] ) {
    67. int tmp = a[j] ;
    68. a[j] = a[i];
    69. a[i] = tmp;
    70. }
    71. }
    72. }
    73. recursive_group_sort ( a, left , mid ) ;
    74. recursive_group_sort ( a, mid+1 , right) ;
    75. }
    76. int main(int argc, char* argv[])
    77. {
    78. int a[10] = {5,2,8,9,3,7,6,0,1,4};
    79. bubble_sort(a,10);
    80. insert_sort(a,10);
    81. select_sort(a,10);
    82. cout<<"recursive group sort "<<endl;
    83. recursive_group_sort( a, 0 , 9 );
    84. print(a,10);
    85. return 0;
    86. }





  • 相关阅读:
    while循环
    赋值运算符、逻辑运算符补充
    布尔类型 基本运算符 if判断
    输入 格式化输出
    计算机基础
    python介绍 编程语言分类及对比 python解释器安装(多版本共存) 变量 数据类型(三种)
    UDP套接字协议
    软件工程个人作业01
    网页版增加信息---添加
    javaWeb项目技术
  • 原文地址:https://www.cnblogs.com/fysola/p/4862560.html
Copyright © 2020-2023  润新知