常用排序算法插入排序

插入排序:

插入排序是假设数列已经按顺序排列,反复将每一个元素插入,如果待插入数据比所有元素大,就直接放到最后;如果比前置元素小,前置元素后移,直至遇到比待插入小的位置。

初始状态,假设数列只有一个元素33

第一步将6插入  6比33小 33后移,6插入到33前面

第二步将-5插入 -5 比33小 33后移 -5比6小 6后移

第三步 将59插入 55 比-5 6 33 都大,直接插入在最后边

第四步 将-12插入 -12比 -5 6 33 59 都小 12 插入最前端

View Code
#include<iostream>
//insertion sort  
using namespace std;
void display(int array[], int n)
{
      for(int count=0;count<n;count++)   //print all items of array
    {
            cout<<array[count]<<'\t';
            }
      cout<<endl;
     } 
int insertion_sort(int array[], int n)         
{
    int temp=0,count=0 ;           //set an temporary  variable
    int k=0;
    cout<<"debug information:"<<endl;   
    for(int i=1;i<n;i++)
    {    
          int temp=array[i];
          int j; 
            for(j=i;j>0 && array[j-1]>temp;j--)
             {          
                  array[j]=array[j-1];                    
             } 
            array[j]=temp;    
       
           display(array,n );
     }
   // cout<<count<<endl;
    return 0;
    }
int main()
{
    int array[5]={33,6,-5,59,-12};
    int num_array=sizeof(array)/sizeof(int);  //获取数组长度 
    cout<<"before sort the array is :"<<endl;   
    display(array,num_array);
    insertion_sort(array,num_array); 
    cout<<"after sort the array is :"<<endl;   
    display(array,num_array);
    system("pause");
    return 0;
    } 

 冒泡法排序算法

http://www.cnblogs.com/tobecrazy/archive/2013/03/13/2958337.html

选择法排序算法

http://www.cnblogs.com/tobecrazy/archive/2013/03/14/2960526.html

转载请注明出处:http://www.cnblogs.com/tobecrazy/

软件测试交流QQ群:312937087 we are QA!

原文地址:https://www.cnblogs.com/tobecrazy/p/2983292.html