思勤无邪

上学时,因我年龄最小,个头也最小,上课时,就像大猩猩堆里的猴一般。如今,这猴偶尔也把最近的一些情况写在这里。

   :: 首页 :: 联系 :: 聚合  :: 管理
  132 Posts :: 1 Stories :: 178 Comments :: 0 Trackbacks

公告

     吾日常三省吾身,曰思、曰勤、曰无邪。

积分与排名

  • 积分 - 177586
  • 排名 - 143

最新随笔

最新评论

阅读排行榜

评论排行榜

// 一些排序函数模板


#include <iostream>
using namespace System;

// 排序算法 函数模板

// 直接插入排序函数模板
template <class T>
void InsertionSort(T A[], int n)
{  int i, j;
   T   temp;
   for (i = 1; i < n; i++)
   {  j = i;
      temp = A[i];
      while (j > 0 && temp < A[j-1])
      {  A[j] = A[j-1];   
         j--;
      }
     A[j] = temp;
   }
}

// 交换位置函数模板
template <class T>
void Swap (T &x, T &y)
{
 T temp;
 temp = x;
 x = y;
 y = temp;
}


// 直接选择排序函数模板
template <class T>
void SelectionSort(T A[], int n)
{  int smallIndex;   
   int i, j;
   for (i = 0; i < n-1; i++)
   {  smallIndex = i;   
      for (j = i+1; j < n; j++)
         if (A[j] < A[smallIndex])
            smallIndex = j;
      Swap(A[i], A[smallIndex]);
   }
}

// 交换排序方法——起泡排序
template <class T>
void BubbleSort(T A[], int n)

 int i,j;            
 int lastExchangeIndex;
 i = n-1;     
 while (i > 0)
 { 
  lastExchangeIndex = 0; 
  for (j = 0; j < i; j++)
  {
   if (A[j+1] < A[j])
   {
    Swap(A[j],A[j+1]);
    lastExchangeIndex = j;    
   }
  }
  i = lastExchangeIndex;
 }
}

// 比较函数指针
// 返回值
//     负值: 第一个参数小于第二个参数
//    0   : 相等
//    正值: 第一个参数大于第二个参数
typedef int (*CFT)(const void*, const void*);

// **************************************
// 对向量base的n个元素按照递增顺序排序
// 用由cmp所指的函数做比较
// 元素的大小是sz
// Shell排序
// **************************************
void ssort(void* base, size_t n, size_t sz, CFT cmp)
{
 for (int gap=n/2; 0<gap; gap/=2)
 {
  for (int i=gap; i<n; i++)
  {
   for (int j=i-gap; 0<=j; j-=gap)
   {
    char* b = static_cast<char*>(base);  // 必须强制
    char* pj = b+j*sz;      // &base[j]
    char* pjg = b+(j+gap)*sz;    // &base[j+gap]
    if (cmp(pjg, pj) < 0)
    {
     // 交换base[j]与base[j+gap]
     for (int k=0; k<sz; k++)
     {
      char temp = pj[k];
      pj[k] = pjg[k];
      pjg[k] = temp;
     }
    }
   }
  }
 }
}

// 比较函数
int compare_int(const void* arg1, const void* arg2)
{
 if (*(int*)arg1 < *(int*)arg2) return -1;
 if (*(int*)arg1 == *(int*)arg2) return 0;
 if (*(int*)arg1 > *(int*)arg2) return 1;
}

void main()
{
 const int MAXSIZE = 20;
 int* iA = new int[MAXSIZE];
 Random* random = new Random;
 for (int i=0; i<MAXSIZE; i++)
 {
  iA[i] = random->Next(100);
 }
 //InsertionSort(iA, 8);
 ssort(iA, MAXSIZE, sizeof(int), compare_int);
 for (int i=0; i<MAXSIZE; i++)
 {
  std::cout<< iA[i] << " ";
 }


 int x;
 std::cin>>x;

}

posted on 2006-05-31 17:26 思勤无邪 阅读(815) 评论(0)  编辑 收藏 引用 所属分类: C++

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理