快速排序 归并排序 算法设计与分析

 Bubble sort: bubbling

Insertion sort: incremental approach (增量靠近)

Merge sort: divide-and conquer(分而治之)

Quick sort: location (元素定位

 

快速排序

int partition(sqlist &l, int low, int high)

{

l.r[0] = l.r[low];

pivorkey = l.r[low].key;

while(low < high){

  while(low <high&&l.r[high].key >= pivotkey) --high;

l.r[low] = l.r[high];

while(low <high&&l.r[low].key<= pivotkey) ++low;

l.r[high] = l.r[low];

 

}

l.r[low] = l.r[0];

return low;

}

 

 

void qsort(sqlist &l, int low, int high){

  if(low < high)

     pivotloc = partition(l, low, high);

  qsort(l, low , pivotloc-1);

  qsort(l, pivotloc+1,high);

}

 

 

 

 

 

1.自底向上算法

  #include <stdio.h>
  #include <time.h>
  void Merge(int *a,int low,int mid,int high)
  {
  int i = low,j = mid + 1,k = 0;
  int *temp = (int *)malloc((high - low + 1)*sizeof(int));
  while(i <= mid && j <= high)
  a[i] < a[j] ? (temp[k++] = a[i++]):(temp[k++] = a[j++]);
  while(i <= mid)
  temp[k++] = a[i++];
  while(j <= high)
  temp[k++] = a[j++];
  memcpy(a + low,temp,(high -low + 1)*sizeof(int));
  free(temp);
  }
  void MergeSort(int *a,int n)
  {
  int length;
  for(length = 1;length < n;length *= 2)
  {
  int i;
  for( i = 0;i + 2*length - 1 <= n - 1;i += 2*length)
  Merge(a,i,i+length-1,i+2*length -1);
  if(i + 2*length - 1 <= n - 1)//尚有两个子文件,其中后一个长度小于length
  Merge(a,i,i +2* length -1,n - 1);
  }
  }
  int main()
  {
  int n;
  cin >> n;
  int *data = new int[n];
  if(!data) exit(1);
  int k = n;
  while(k --)
  {
  cin >> data[n-k-1];
  }
  clock_t s = clock();
  MergeSort(data, n);
  clock_t e = clock();
  k = n;
  while(k --){
  cout << data[n-k-1] << ' ';
  }
  cout << endl;
  cout << "the algrothem used " << e-s << " miliseconds."<< endl;
  delete data;
  return 0;

  }

 

void mergeSort(struct RECORD arr_buffer[][40])
{
 int length;
 for (length = 1; length < _FILE_NUM_ ; length *= 2 )
 {
  MergePass(arr_buffer, length);
  
 }
}

 

void MergePass(SeqList R,int length)
{
int i;
for(i=1;i+2*length-1<=n;i=i+2*length)
Merge(R,i,i+length-1,i+2*length-1);

if(i+length-1<n)
Merge(R,i,i+length-1,n);

}

 

 void Merge(int *a,int low,int mid,int high)

  {

  int i = low,j = mid + 1,k = 0;

  int *temp = (int *)malloc((high - low + 1)*sizeof(int));

  while(i <= mid && j <= high)

  a[i] < a[j] ? (temp[k++] = a[i++]):(temp[k++] = a[j++]);

  while(i <= mid)

  temp[k++] = a[i++];

  while(j <= high)

  temp[k++] = a[j++];

  memcpy(a + low,temp,(high -low + 1)*sizeof(int));

  free(temp);

  }







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值