插入排序和冒泡排序

 

//插入排序
void insertSort( int a[], int N)
{
     int temp;
     int j;
     //从第二个元素开始
     for ( int i = 1 ; i < N; i++) {
         if (a[i] >= a[i- 1 ]) continue;
         temp = a[i];
         //与前面的元素比较,看是否需要插入
         for (j = i - 1 ; a[j] > temp; j--) {
             if (j< 0 ) break;
             a[j+ 1 ] = a[j]; //后移
         }
         a[j+ 1 ] = temp;
     }
     
     for ( int i = 0 ; i < N; i++) {
         NSLog( @"insert sort::%d" , a[i]);
     }
}
 
void binaryInsertSort( int a[], int N)
{
     
}
 
//冒泡排序
void bubbleSort( int *a, int N)
{
     int temp;
     for ( int i = 0 ; i < N - 1 ; i++) {
         for ( int j = 0 ; j < N - i - 1 ; j++) {
             if (a[j] > a[j+ 1 ]) {
                 temp = a[j];
                 a[j] = a[j+ 1 ];
                 a[j+ 1 ] = temp;
             }
         }
     }
     for ( int i = 0 ; i < N; i++) {
         NSLog( @"bubble sort::%d" , a[i]);
     }
}

你可能感兴趣的:(冒泡排序)